<div class="body" role="main"><div class="section" id="module-urllib.request"><h1><span class="yiyi-st" id="yiyi-10">21.6. <a class="reference internal" href="#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal"><span class="pre">urllib.request</span></code></a>  —— 用于打开URL的可扩展库</span></h1><p><span class="yiyi-st" id="yiyi-11"><strong>源代码：</strong> <a class="reference external" href="https://hg.python.org/cpython/file/3.5/Lib/urllib/request.py">Lib / urllib / request.py</a></span></p><p><span class="yiyi-st" id="yiyi-12"><a class="reference internal" href="#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal"><span class="pre">urllib.request</span></code></a> 模块定义了在基本和摘要式身份验证、 重定向、 cookies等应用中打开 Url (主要是 HTTP) 的函数和类。</span></p><div class="admonition seealso"><p class="first admonition-title"><span class="yiyi-st" id="yiyi-13">也可以看看</span></p><p class="last"><span class="yiyi-st" id="yiyi-14"><a class="reference external" href="https://requests.readthedocs.org/">Requests 包</a> 建议用作高级的非底层的 HTTP 客户端接口。</span></p></div><p><span class="yiyi-st" id="yiyi-15"><a class="reference internal" href="#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal"><span class="pre">urllib.request</span></code></a> 模块定义了以下函数︰</span></p><dl class="function"><dt id="urllib.request.urlopen"><span class="yiyi-st" id="yiyi-16"> <code class="descclassname">urllib.request.</code><code class="descname">urlopen</code><span class="sig-paren">(</span><em>url</em>, <em>data=None</em>, <span class="optional">[</span><em>timeout</em>, <span class="optional">]</span><em>*</em>, <em>cafile=None</em>, <em>capath=None</em>, <em>cadefault=False</em>, <em>context=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-17">打开<em>url</em>参数传进来的网址，既可以是一个字符串，又可以是一个<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>对象。</span></p><p><span class="yiyi-st" id="yiyi-18">当你有额外的数据要发送到服务器，那<em>data</em>参数必须是一个有数据的bytes对象，否则为<code class="docutils literal"><span class="pre">None</span></code>。</span><span class="yiyi-st" id="yiyi-19">其实<em>data</em> 也可以是一个可迭代的对象，若是，则headers中必须带 Content-Length 参数。</span><span class="yiyi-st" id="yiyi-20">若本次HTTP请求要用POST方法，<em>data</em>必须有数据；若为GET方法时， <em>data</em>写None就行。</span></p><p><span class="yiyi-st" id="yiyi-21"><em>data</em>参数应该是一个标准的<em class="mimetype">application/x-www-form-urlencoded</em> 格式的缓冲区.</span><span class="yiyi-st" id="yiyi-22"><a class="reference internal" href="urllib.parse.html#urllib.parse.urlencode" title="urllib.parse.urlencode"><code class="xref py py-func docutils literal"><span class="pre">urllib.parse.urlencode()</span></code></a> 函数接受一个映射或者一个内含一个两元素元组的序列，并且返回一个该格式的ASCII字符串。</span><span class="yiyi-st" id="yiyi-23"><em>data</em>参数在使用之前应该被编码成bytes。</span></p><p><span class="yiyi-st" id="yiyi-24">urllib.request 模块参照 HTTP/1.1 标准， 并且在HTTP请求中，头信息可以有<code class="docutils literal"><span class="pre">Connection:close</span></code>。</span></p><p><span class="yiyi-st" id="yiyi-25"><em>timeout</em> 参数是可选的。它指定一个超时时间。若超过该时间，任何操作都会被阻止，如链接超时（如果没有指定，则会默认值为socket._GLOBAL_DEFAULT_TIMEOUT）。</span><span class="yiyi-st" id="yiyi-26">其实这个参数仅仅对http、https和ftp连接有效。</span></p><p><span class="yiyi-st" id="yiyi-27">如果指定了 <em>context</em> 参数，则它必须是一个描述了各种SSL选项的 <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal"><span class="pre">ssl.SSLContext</span></code></a> 实例。</span><span class="yiyi-st" id="yiyi-28">更详细内容，请点击 <a class="reference internal" href="http.client.html#http.client.HTTPSConnection" title="http.client.HTTPSConnection"><code class="xref py py-class docutils literal"><span class="pre">HTTPSConnection</span></code></a> 。</span></p><p><span class="yiyi-st" id="yiyi-29"><em>cafile</em> 和 <em>capath</em> 参数都是可选的。他们应该被指定一组“HTTPS请求”所需要的受信任的CA 证书。</span><span class="yiyi-st" id="yiyi-30"><em>cafile</em> 参数应该指向文件，该文件包含了一大堆CA证书，而<em>capath</em> 参数应该指向一个目录，该目录包含了散列过的证书。</span><span class="yiyi-st" id="yiyi-31">更多的信息，可以从 <a class="reference internal" href="ssl.html#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code class="xref py py-meth docutils literal"><span class="pre">ssl.SSLContext.load_verify_locations()</span></code></a> 里找到。</span></p><p><span class="yiyi-st" id="yiyi-32"><em>cadefault</em> 参数不能用了，所以不用管它了，吼吼~~</span></p><p><span class="yiyi-st" id="yiyi-33">这个urlopen函数总是返回一个对象，这个对象能被<a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a>（上下文管理器）中的一些方法使用，如：</span></p><ul class="simple"><li><span class="yiyi-st" id="yiyi-34"><code class="xref py py-meth docutils literal"><span class="pre">geturl()</span></code> — 返回一个资源索引的URL，通常重定向后的URL照样能get到。</span></li><li><span class="yiyi-st" id="yiyi-35"><code class="xref py py-meth docutils literal"><span class="pre">info()</span></code> — 返回页面的元信息，如头信息。像 <a class="reference internal" href="email.parser.html#email.message_from_string" title="email.message_from_string"><code class="xref py py-func docutils literal"><span class="pre">email.message_from_string()</span></code></a> 实例的格式一样。（请看 <a class="reference external" href="https://www.cs.tut.fi/~jkorpela/http.html">Quick Reference to HTTP Headers</a>）</span></li><li><span class="yiyi-st" id="yiyi-36"><code class="xref py py-meth docutils literal"><span class="pre">getcode()</span></code> – 返回响应后，HTTP的状态码。</span></li></ul><p><span class="yiyi-st" id="yiyi-37">对于HTTP和HTTPS网址，此函数会返回稍微修改的<a class="reference internal" href="http.client.html#http.client.HTTPResponse" title="http.client.HTTPResponse"><code class="xref py py-class docutils literal"><span class="pre">http.client.HTTPResponse</span></code></a>对象。</span><span class="yiyi-st" id="yiyi-38">除了上述的三种新方法外，还有一个叫msg的属性，包含着和<a class="reference internal" href="http.client.html#http.client.HTTPResponse.reason" title="http.client.HTTPResponse.reason"><code class="xref py py-attr docutils literal"><span class="pre">reason</span></code></a>属性一样的信息 — 原因短语从服务器上返回 — 代替了<a class="reference internal" href="http.client.html#http.client.HTTPResponse" title="http.client.HTTPResponse"><code class="xref py py-class docutils literal"><span class="pre">HTTPResponse</span></code></a>文档里指定的那些响应头。</span></p><p><span class="yiyi-st" id="yiyi-39">对于 FTP，文件，和数据的URL，都显式地由以前的 <a class="reference internal" href="#urllib.request.URLopener" title="urllib.request.URLopener"><code class="xref py py-class docutils literal"><span class="pre">URLopener</span></code></a> 和 <a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a> 类处理，处理它们的函数，返回一个 <code class="xref py py-class docutils literal"><span class="pre">urllib.response.addinfourl</span></code> 对象。</span></p><p><span class="yiyi-st" id="yiyi-40">如果协议错误，则引发<a class="reference internal" href="urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal"><span class="pre">URLError</span></code></a>。</span></p><p><span class="yiyi-st" id="yiyi-41">注意：如果没有服务器来处理这个请求，那么可能会返回<code class="docutils literal"><span class="pre">None</span></code> 值。(尽管有默认被安装的全局 <a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a> 使用 <a class="reference internal" href="#urllib.request.UnknownHandler" title="urllib.request.UnknownHandler"><code class="xref py py-class docutils literal"><span class="pre">UnknownHandler</span></code></a> 来确保这种情况不发生)。</span></p><p><span class="yiyi-st" id="yiyi-42">另外，当代理被检测到，(例如，当一个像<span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal"><span class="pre">http_proxy</span></code>的<code class="docutils literal"><span class="pre">*_proxy</span></code> 环境变量 被设置), <a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler</span></code></a> 会被默认安装以确保请求会通过代理来处理。</span></p><p><span class="yiyi-st" id="yiyi-43">在python2.6或者更早版本中遗留的 <code class="docutils literal"><span class="pre">urllib.urlopen</span></code>函数已经被停用； <a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urllib.request.urlopen()</span></code></a> 函数和旧版本python中的<code class="docutils literal"><span class="pre">urllib2.urlopen</span></code>函数其实是相同的。</span><span class="yiyi-st" id="yiyi-44">通过向<code class="docutils literal"><span class="pre">urllib.urlopen</span></code>传递一个字典参数得到的Proxy handing，能够通过使用<a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler</span></code></a> 对象来获取。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-45"><span class="versionmodified">在3.2版本中的更改：</span><em>cafile</em> 和<em>capath</em> 被增加。</span></p></div><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-46"><span class="versionmodified">在版本3.2中已更改：</span>现在支持HTTPS虚拟主机（如果可能（即，如果<a class="reference internal" href="ssl.html#ssl.HAS_SNI" title="ssl.HAS_SNI"><code class="xref py py-data docutils literal"><span class="pre">ssl.HAS_SNI</span></code></a>为true）。</span></p></div><div class="versionadded"><p><span class="yiyi-st" id="yiyi-47"><span class="versionmodified">3.2版本中新增功能：</span><em>data</em>参数可以是一个iterable对象。</span></p></div><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-48"><span class="versionmodified">在3.3版本中的更改：</span><em>cadefault</em> 被增加。</span></p></div><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-49"><span class="versionmodified">在3.4.3版本中的更改：</span><em>context</em> 被增加。</span></p></div></dd></dl><dl class="function"><dt id="urllib.request.install_opener"><span class="yiyi-st" id="yiyi-50"> <code class="descclassname">urllib.request.</code><code class="descname">install_opener</code><span class="sig-paren">(</span><em>opener</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-51">安装<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>实例作为默认全局启动器。</span><span class="yiyi-st" id="yiyi-52">安装启动器只有当你想要urlopen使用启动器；否则，只需调用<a class="reference internal" href="#urllib.request.OpenerDirector.open" title="urllib.request.OpenerDirector.open"><code class="xref py py-meth docutils literal"><span class="pre">OpenerDirector.open()</span></code></a>而不是<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>。</span><span class="yiyi-st" id="yiyi-53">代码不检查真实的<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>，任何具有适当接口的类都可以工作。</span></p></dd></dl><dl class="function"><dt id="urllib.request.build_opener"><span class="yiyi-st" id="yiyi-54"> <code class="descclassname">urllib.request.</code><code class="descname">build_opener</code><span class="sig-paren">(</span><span class="optional">[</span><em>handler</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-55">返回<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>实例，按所给定的顺序链接处理程序。</span><span class="yiyi-st" id="yiyi-56"><em>handler</em>可以是<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>的实例或<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>的子类（在这种情况下，必须可以调用没有任何参数的构造函数） 。</span><span class="yiyi-st" id="yiyi-57">以下类的实例将在<em>handler</em>前面，除非<em>handler</em>包含它们，它们的实例或它们的子类：<a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler </span></code></a>（如果检测到代理设置），<a class="reference internal" href="#urllib.request.UnknownHandler" title="urllib.request.UnknownHandler"><code class="xref py py-class docutils literal"><span class="pre">UnknownHandler</span></code></a>，<a class="reference internal" href="#urllib.request.HTTPHandler" title="urllib.request.HTTPHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPHandler</span></code></a>，<a class="reference internal" href="#urllib.request.HTTPDefaultErrorHandler" title="urllib.request.HTTPDefaultErrorHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPDefaultErrorHandler</span></code></a>，<a class="reference internal" href="#urllib.request.HTTPRedirectHandler" title="urllib.request.HTTPRedirectHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPRedirectHandler</span></code></a>，<a class="reference internal" href="#urllib.request.FTPHandler" title="urllib.request.FTPHandler"><code class="xref py py-class docutils literal"><span class="pre">FTPHandler </span></code></a>，<a class="reference internal" href="#urllib.request.FileHandler" title="urllib.request.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a>，<a class="reference internal" href="#urllib.request.HTTPErrorProcessor" title="urllib.request.HTTPErrorProcessor"><code class="xref py py-class docutils literal"><span class="pre">HTTPErrorProcessor</span></code></a>。</span></p><p><span class="yiyi-st" id="yiyi-58">如果 Python 安装了 SSL 支持 （即，如果 <a class="reference internal" href="ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal"><span class="pre">ssl</span></code></a> 模块可以导入），还将添加 <a class="reference internal" href="#urllib.request.HTTPSHandler" title="urllib.request.HTTPSHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPSHandler</span></code></a>。</span></p><p><span class="yiyi-st" id="yiyi-59"><a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a> 子类也可能更改其 <code class="xref py py-attr docutils literal"><span class="pre">handler_order</span></code> 属性来修改其处理程序列表中的位置。</span></p></dd></dl><dl class="function"><dt id="urllib.request.pathname2url"><span class="yiyi-st" id="yiyi-60"> <code class="descclassname">urllib.request.</code><code class="descname">pathname2url</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-61">将路径名<em>path</em>从本地语法转换为URL的路径组件中使用的形式。</span><span class="yiyi-st" id="yiyi-62">这不会产生一个完整的URL。</span><span class="yiyi-st" id="yiyi-63">返回值已使用<a class="reference internal" href="urllib.parse.html#urllib.parse.quote" title="urllib.parse.quote"><code class="xref py py-func docutils literal"><span class="pre">quote()</span></code></a>函数引用。</span></p></dd></dl><dl class="function"><dt id="urllib.request.url2pathname"><span class="yiyi-st" id="yiyi-64"> <code class="descclassname">urllib.request.</code><code class="descname">url2pathname</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-65">将路径组件<em>路径</em>从百分比编码的URL转换为路径的本地语法。</span><span class="yiyi-st" id="yiyi-66">这不接受完整的URL。</span><span class="yiyi-st" id="yiyi-67">该函数使用<a class="reference internal" href="urllib.parse.html#urllib.parse.unquote" title="urllib.parse.unquote"><code class="xref py py-func docutils literal"><span class="pre">unquote()</span></code></a>来解码<em>路径</em>。</span></p></dd></dl><dl class="function"><dt id="urllib.request.getproxies"><span class="yiyi-st" id="yiyi-68"> <code class="descclassname">urllib.request.</code><code class="descname">getproxies</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-69">这个帮助函数返回一个方案到代理服务器URL映射的字典。</span><span class="yiyi-st" id="yiyi-70">它以大小写不敏感的方式为所有操作系统首先扫描名为<code class="docutils literal"><span class="pre">&lt;scheme&gt;_proxy</span></code>的变量的环境，并且当它找不到它时，查找Mac OSX System Configuration for Mac中的代理信息适用于Windows的OS X和Windows系统注册表。</span><span class="yiyi-st" id="yiyi-71">如果小写和大写环境变量都存在（并且不同意），则小写是首选。</span></p><span class="yiyi-st" id="yiyi-72"> <blockquote> <div><div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">If the environment variable <code class="docutils literal"><span class="pre">REQUEST_METHOD</span></code> is set, which usually indicates your script is running in a CGI environment, the environment variable <code class="docutils literal"><span class="pre">HTTP_PROXY</span></code> (uppercase <code class="docutils literal"><span class="pre">_PROXY</span></code>) will be ignored. This is because that variable can be injected by a client using the “Proxy:” HTTP header. If you need to use an HTTP proxy in a CGI environment, either use <code class="docutils literal"><span class="pre">ProxyHandler</span></code> explicitly, or make sure the variable name is in lowercase (or at least the <code class="docutils literal"><span class="pre">_proxy</span></code> suffix).</p> </div> </div></blockquote></span></dd></dl><p><span class="yiyi-st" id="yiyi-73">提供以下类：</span></p><dl class="class"><dt id="urllib.request.Request"><span class="yiyi-st" id="yiyi-74"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">Request</code><span class="sig-paren">(</span><em>url</em>, <em>data=None</em>, <em>headers={}</em>, <em>origin_req_host=None</em>, <em>unverifiable=False</em>, <em>method=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-75">这个类是一个URL请求的抽象。</span></p><p><span class="yiyi-st" id="yiyi-76"><em>url</em>应为包含有效网址的字符串。</span></p><p><span class="yiyi-st" id="yiyi-77"><em>data</em>必须是指定要发送到服务器的附加数据的字节对象，如果不需要此类数据，则<code class="docutils literal"><span class="pre">None</span></code>。</span><span class="yiyi-st" id="yiyi-78">目前只有POST请求将<em>data</em>作为参数，GET请求不能使用<em>data</em>作为参数进行HTTP请求。</span><span class="yiyi-st" id="yiyi-79"><em>data</em>应为标准<em class="mimetype">application/x-www-form-urlencoded</em>格式的缓冲区。</span><span class="yiyi-st" id="yiyi-80"><a class="reference internal" href="urllib.parse.html#urllib.parse.urlencode" title="urllib.parse.urlencode"><code class="xref py py-func docutils literal"><span class="pre">urllib.parse.urlencode()</span></code></a>函数接受2元组的映射或序列，并返回此格式的ASCII字符串。</span><span class="yiyi-st" id="yiyi-81">在用作<em>data</em>参数之前，应将其编码为字节。</span></p><p><span class="yiyi-st" id="yiyi-82"><em>headers</em>应该是一个字典，并且将被视为<a class="reference internal" href="#urllib.request.Request.add_header" title="urllib.request.Request.add_header"><code class="xref py py-meth docutils literal"><span class="pre">add_header()</span></code></a>以每个键和值作为参数被调用。</span><span class="yiyi-st" id="yiyi-83">这通常用于“欺骗”<code class="docutils literal"><span class="pre">User-Agent</span></code>标头值，浏览器使用它来标识自身 - 某些HTTP服务器只允许来自常见浏览器的请求，而不是脚本。</span><span class="yiyi-st" id="yiyi-84">例如，Mozilla Firefox可能将其标识为<code class="docutils literal"><span class="pre">“Mozilla / 5.0</span> <span class="pre">（X11；</span> <span class="pre">U；</span> <span class="pre">Linux</span> <span class="pre">i686）</span> <span class="pre">Gecko / 20071127</span> <span class="pre">Firefox / 2.0.0.11“</span></code>，而<a class="reference internal" href="urllib.html#module-urllib" title="urllib"><code class="xref py py-mod docutils literal"><span class="pre">urllib</span></code></a>代理字符串是<code class="docutils literal"><span class="pre">“Python-urllib / 2.6”</span></code>（在Python 2.6上）。</span></p><p><span class="yiyi-st" id="yiyi-85">使用<code class="docutils literal"><span class="pre">Content-Type</span></code>头与<em>数据</em>参数的示例将发送像<code class="docutils literal"><span class="pre">{“Content-Type”：</span> <span class="pre">“application / x-www-form-urlencoded”}</span></code>。</span></p><p><span class="yiyi-st" id="yiyi-86">最后两个参数仅对正确处理第三方HTTP Cookie感兴趣：</span></p><p><span class="yiyi-st" id="yiyi-87"><em>origin_req_host</em>应该是<span class="target" id="index-1"></span> <a class="rfc reference external" href="https://tools.ietf.org/html/rfc2965.html"><strong>RFC 2965</strong></a>定义的原始事务的请求主机。</span><span class="yiyi-st" id="yiyi-88">它默认为<code class="docutils literal"><span class="pre">http.cookiejar.request_host(self)</span></code>。</span><span class="yiyi-st" id="yiyi-89">这是用户发起的原始请求的主机名或IP地址。</span><span class="yiyi-st" id="yiyi-90">例如，如果请求是针对HTML文档中的图像的，则该请求应该是包含图像的页面请求的请求主机。</span></p><p><span class="yiyi-st" id="yiyi-91"><em>unverifiable</em>应指示该请求是否是无法验证的，如RFC 2965所定义。</span><span class="yiyi-st" id="yiyi-92">它默认为<code class="docutils literal"><span class="pre">False</span></code>。</span><span class="yiyi-st" id="yiyi-93">无法验证的请求是其用户没有选择批准的URL。</span><span class="yiyi-st" id="yiyi-94">例如，如果请求是针对HTML文档中的图像，并且用户无权批准自动获取图像，则应该是正确的。</span></p><p><span class="yiyi-st" id="yiyi-95"><em>method</em>应为指示将使用的HTTP请求方法的字符串（例如，</span><span class="yiyi-st" id="yiyi-96"><code class="docutils literal"><span class="pre">'HEAD'</span></code></span><span class="yiyi-st" id="yiyi-97">如果提供，它的值存储在<a class="reference internal" href="#urllib.request.Request.method" title="urllib.request.Request.method"><code class="xref py py-attr docutils literal"><span class="pre">method</span></code></a>属性中，并由<a class="reference internal" href="#urllib.request.Request.get_method" title="urllib.request.Request.get_method"><code class="xref py py-meth docutils literal"><span class="pre">get_method()</span></code></a>使用。</span><span class="yiyi-st" id="yiyi-98">子类可以通过在类本身中设置<a class="reference internal" href="#urllib.request.Request.method" title="urllib.request.Request.method"><code class="xref py py-attr docutils literal"><span class="pre">method</span></code></a>属性来指示默认方法。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-99"><span class="versionmodified">在版本3.3中改变：</span> <a class="reference internal" href="#urllib.request.Request.method" title="urllib.request.Request.method"><code class="xref py py-attr docutils literal"><span class="pre">Request.method</span></code></a>参数被添加到Request类中。</span></p></div><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-100"><span class="versionmodified">Changed in version 3.4: </span>Default <a class="reference internal" href="#urllib.request.Request.method" title="urllib.request.Request.method"><code class="xref py py-attr docutils literal"><span class="pre">Request.method</span></code></a> may be indicated at the class level.</span></p></div></dd></dl><dl class="class"><dt id="urllib.request.OpenerDirector"><span class="yiyi-st" id="yiyi-101"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">OpenerDirector</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-102"><a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>类通过<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>链接在一起打开网址。</span><span class="yiyi-st" id="yiyi-103">它管理处理程序的链接，并从错误中恢复。</span></p></dd></dl><dl class="class"><dt id="urllib.request.BaseHandler"><span class="yiyi-st" id="yiyi-104"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">BaseHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-105">这是所有注册处理程序的基类 - 并且只处理注册的简单机制。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPDefaultErrorHandler"><span class="yiyi-st" id="yiyi-106"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPDefaultErrorHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-107">定义HTTP错误响应的默认处理程序的类；所有响应将变为<a class="reference internal" href="urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal"><span class="pre">HTTPError</span></code></a>异常。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPRedirectHandler"><span class="yiyi-st" id="yiyi-108"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPRedirectHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-109">一个类来处理重定向。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPCookieProcessor"><span class="yiyi-st" id="yiyi-110"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPCookieProcessor</code><span class="sig-paren">(</span><em>cookiejar=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-111">一个类来处理HTTP Cookie。</span></p></dd></dl><dl class="class"><dt id="urllib.request.ProxyHandler"><span class="yiyi-st" id="yiyi-112"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">ProxyHandler</code><span class="sig-paren">(</span><em>proxies=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-113">导致请求通过代理。</span><span class="yiyi-st" id="yiyi-114">如果给出了<em>代理</em>，它必须是一个字典映射到代理的URL的协议名称。</span><span class="yiyi-st" id="yiyi-115">缺省值是从环境变量<span class="target" id="index-2"></span> <code class="xref std std-envvar docutils literal"><span class="pre">&lt;protocol&gt;_proxy</span></code>中读取代理列表。</span><span class="yiyi-st" id="yiyi-116">如果未设置代理环境变量，则在Windows环境中，代理设置可从注册表的“Internet设置”部分获得，而在Mac OS X环境中，将从OS X系统配置框架中检索代理信息。</span></p><p><span class="yiyi-st" id="yiyi-117">禁用自动检测代理传递空字典。</span></p><p><span class="yiyi-st" id="yiyi-118">可以使用<span class="target" id="index-3"></span> <code class="xref std std-envvar docutils literal"><span class="pre">no_proxy</span></code>环境变量指定不应通过代理访问的主机；如果设置，它应该是逗号分隔的主机名后缀列表，可选地附加<code class="docutils literal"><span class="pre">:port</span></code>，例如<code class="docutils literal"><span class="pre">cern.ch,ncsa.uiuc.edu,some.host:8080</span></code></span></p><span class="yiyi-st" id="yiyi-119"> <blockquote> <div><div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last"><code class="docutils literal"><span class="pre">HTTP_PROXY</span></code> will be ignored if a variable <code class="docutils literal"><span class="pre">REQUEST_METHOD</span></code> is set; see the documentation on <a class="reference internal" href="#urllib.request.getproxies" title="urllib.request.getproxies"><code class="xref py py-func docutils literal"><span class="pre">getproxies()</span></code></a>.</p> </div> </div></blockquote></span></dd></dl><dl class="class"><dt id="urllib.request.HTTPPasswordMgr"><span class="yiyi-st" id="yiyi-120"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPPasswordMgr</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-121">保持<code class="docutils literal"><span class="pre">（realm，</span> <span class="pre">uri）</span> <span class="pre"> - &gt;＆lt； / t3&gt; <span class="pre">（用户，</span> <span class="pre">密码）</span></span></code>映​​射。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPPasswordMgrWithDefaultRealm"><span class="yiyi-st" id="yiyi-122"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPPasswordMgrWithDefaultRealm</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-123">保持<code class="docutils literal"><span class="pre">（realm，</span> <span class="pre">uri）</span> <span class="pre"> - &gt;＆lt； / t3&gt; <span class="pre">（用户，</span> <span class="pre">密码）</span></span></code>映​​射。</span><span class="yiyi-st" id="yiyi-124">一个<code class="docutils literal"><span class="pre">None</span></code>的领域被认为是一个通用领域，如果没有其他领域适合，就会搜索它。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPPasswordMgrWithPriorAuth"><span class="yiyi-st" id="yiyi-125"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPPasswordMgrWithPriorAuth</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-126">一个<a class="reference internal" href="#urllib.request.HTTPPasswordMgrWithDefaultRealm" title="urllib.request.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a>的变体，它也有一个<code class="docutils literal"><span class="pre">uri</span> <span class="pre"> - &gt;＆gt；</span> <span class="pre">is_authenticated</span></code>映射。</span><span class="yiyi-st" id="yiyi-127">BasicAuth处理程序可以使用它来确定何时立即发送认证凭证，而不是先等待<code class="docutils literal"><span class="pre">401</span></code>响应。</span></p><div class="versionadded"><p><span class="yiyi-st" id="yiyi-128"><span class="versionmodified">版本3.5中的新功能。</span></span></p></div></dd></dl><dl class="class"><dt id="urllib.request.AbstractBasicAuthHandler"><span class="yiyi-st" id="yiyi-129"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">AbstractBasicAuthHandler</code><span class="sig-paren">(</span><em>password_mgr=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-130">这是一个mixin类，可以帮助远程主机和代理的HTTP身份验证。</span><span class="yiyi-st" id="yiyi-131"><em>password_mgr</em>（如果给定）应该是与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>兼容的内容；有关必须支持的接口的信息，请参阅<a class="reference internal" href="#http-password-mgr"><span>HTTPPasswordMgr对象</span></a>一节。</span><span class="yiyi-st" id="yiyi-132">如果<em>passwd_mgr</em>还提供<code class="docutils literal"><span class="pre">is_authenticated</span></code>和<code class="docutils literal"><span class="pre">update_authenticated</span></code>方法（请参阅<a class="reference internal" href="#http-password-mgr-with-prior-auth"><span>HTTPPasswordMgrWithPriorAuth Objects</span></a>），则处理程序将使用<code class="docutils literal"><span class="pre">is_authenticated</span></code>结果以确定是否发送认证凭证与请求。</span><span class="yiyi-st" id="yiyi-133">如果<code class="docutils literal"><span class="pre">is_authenticated</span></code>为URI返回<code class="docutils literal"><span class="pre">True</span></code>，则发送凭证。</span><span class="yiyi-st" id="yiyi-134">如果<code class="docutils literal"><span class="pre">is_authenticated</span></code>为<code class="docutils literal"><span class="pre">False</span></code>，则不会发送凭证，然后如果收到<code class="docutils literal"><span class="pre">401</span></code>响应，请求将与认证凭证一起重新发送。</span><span class="yiyi-st" id="yiyi-135">如果认证成功，则调用<code class="docutils literal"><span class="pre">update_authenticated</span></code>来为URI设置<code class="docutils literal"><span class="pre">is_authenticated</span></code> <code class="docutils literal"><span class="pre">True</span></code>，以便随后对URI或其任何超级URI将自动包含认证凭证。</span></p><div class="versionadded"><p><span class="yiyi-st" id="yiyi-136"><span class="versionmodified">3.5版新增：</span>新增<code class="docutils literal"><span class="pre">is_authenticated</span></code>支持。</span></p></div></dd></dl><dl class="class"><dt id="urllib.request.HTTPBasicAuthHandler"><span class="yiyi-st" id="yiyi-137"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPBasicAuthHandler</code><span class="sig-paren">(</span><em>password_mgr=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-138">处理与远程主机的身份验证。</span><span class="yiyi-st" id="yiyi-139"><em>password_mgr</em>（如果给定）应该是与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>兼容的内容；有关必须支持的接口的信息，请参阅<a class="reference internal" href="#http-password-mgr"><span>HTTPPasswordMgr对象</span></a>一节。</span><span class="yiyi-st" id="yiyi-140">当出现错误的认证方案时，HTTPBasicAuthHandler将引发<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal"><span class="pre">ValueError</span></code></a>。</span></p></dd></dl><dl class="class"><dt id="urllib.request.ProxyBasicAuthHandler"><span class="yiyi-st" id="yiyi-141"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">ProxyBasicAuthHandler</code><span class="sig-paren">(</span><em>password_mgr=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-142">处理与代理的身份验证。</span><span class="yiyi-st" id="yiyi-143"><em>password_mgr</em>（如果给定）应该是与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>兼容的内容；有关必须支持的接口的信息，请参阅<a class="reference internal" href="#http-password-mgr"><span>HTTPPasswordMgr对象</span></a>一节。</span></p></dd></dl><dl class="class"><dt id="urllib.request.AbstractDigestAuthHandler"><span class="yiyi-st" id="yiyi-144"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">AbstractDigestAuthHandler</code><span class="sig-paren">(</span><em>password_mgr=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-145">这是一个mixin类，可以帮助远程主机和代理的HTTP身份验证。</span><span class="yiyi-st" id="yiyi-146"><em>password_mgr</em>（如果给定）应该是与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>兼容的内容；有关必须支持的接口的信息，请参阅<a class="reference internal" href="#http-password-mgr"><span>HTTPPasswordMgr对象</span></a>一节。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPDigestAuthHandler"><span class="yiyi-st" id="yiyi-147"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPDigestAuthHandler</code><span class="sig-paren">(</span><em>password_mgr=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-148">处理与远程主机的身份验证。</span><span class="yiyi-st" id="yiyi-149"><em>password_mgr</em>（如果给定）应该是与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>兼容的内容；有关必须支持的接口的信息，请参阅<a class="reference internal" href="#http-password-mgr"><span>HTTPPasswordMgr对象</span></a>一节。</span><span class="yiyi-st" id="yiyi-150">当同时添加摘要式身份验证处理程序和基本身份验证处理程序时，首先会尝试摘要式身份验证。</span><span class="yiyi-st" id="yiyi-151">如果摘要认证再次返回40x响应，则将其发送到基本认证处理程序以处理。</span><span class="yiyi-st" id="yiyi-152">当使用Digest或Basic以外的身份验证方案时，此Handler方法将引发<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal"><span class="pre">ValueError</span></code></a>。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-153"><span class="versionmodified">Changed in version 3.3: </span>Raise <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal"><span class="pre">ValueError</span></code></a> on unsupported Authentication Scheme.</span></p></div></dd></dl><dl class="class"><dt id="urllib.request.ProxyDigestAuthHandler"><span class="yiyi-st" id="yiyi-154"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">ProxyDigestAuthHandler</code><span class="sig-paren">(</span><em>password_mgr=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-155">处理与代理的身份验证。</span><span class="yiyi-st" id="yiyi-156"><em>password_mgr</em>（如果给定）应该是与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>兼容的内容；有关必须支持的接口的信息，请参阅<a class="reference internal" href="#http-password-mgr"><span>HTTPPasswordMgr对象</span></a>一节。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPHandler"><span class="yiyi-st" id="yiyi-157"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-158">一个处理HTTP URL打开的类。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPSHandler"><span class="yiyi-st" id="yiyi-159"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPSHandler</code><span class="sig-paren">(</span><em>debuglevel=0</em>, <em>context=None</em>, <em>check_hostname=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-160">一个处理HTTPS URL打开的类。</span><span class="yiyi-st" id="yiyi-161"><em>context</em>和<em>check_hostname</em>的含义与<a class="reference internal" href="http.client.html#http.client.HTTPSConnection" title="http.client.HTTPSConnection"><code class="xref py py-class docutils literal"><span class="pre">http.client.HTTPSConnection</span></code></a>中的含义相同。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-162"><span class="versionmodified">Changed in version 3.2: </span><em>context</em> and <em>check_hostname</em> were added.</span></p></div></dd></dl><dl class="class"><dt id="urllib.request.FileHandler"><span class="yiyi-st" id="yiyi-163"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">FileHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-164">打开本地文件。</span></p></dd></dl><dl class="class"><dt id="urllib.request.DataHandler"><span class="yiyi-st" id="yiyi-165"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">DataHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-166">打开数据网址。</span></p><div class="versionadded"><p><span class="yiyi-st" id="yiyi-167"><span class="versionmodified">版本3.4中的新功能。</span></span></p></div></dd></dl><dl class="class"><dt id="urllib.request.FTPHandler"><span class="yiyi-st" id="yiyi-168"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">FTPHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-169">打开FTP URL。</span></p></dd></dl><dl class="class"><dt id="urllib.request.CacheFTPHandler"><span class="yiyi-st" id="yiyi-170"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">CacheFTPHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-171">打开FTP URL，保持打开的FTP连接缓存，以尽量减少延迟。</span></p></dd></dl><dl class="class"><dt id="urllib.request.UnknownHandler"><span class="yiyi-st" id="yiyi-172"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">UnknownHandler</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-173">一个全能的类来处理未知的URL。</span></p></dd></dl><dl class="class"><dt id="urllib.request.HTTPErrorProcessor"><span class="yiyi-st" id="yiyi-174"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">HTTPErrorProcessor</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-175">处理HTTP错误响应。</span></p></dd></dl><div class="section" id="request-objects"><h2><span class="yiyi-st" id="yiyi-176">21.6.1. </span><span class="yiyi-st" id="yiyi-177">请求对象</span></h2><p><span class="yiyi-st" id="yiyi-178">以下方法描述<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>的公共接口，因此均可能在子类中被覆盖。</span><span class="yiyi-st" id="yiyi-179">它还定义了几个公共属性，客户端可以使用这些属性来检查解析的请求。</span></p><dl class="attribute"><dt id="urllib.request.Request.full_url"><span class="yiyi-st" id="yiyi-180"> <code class="descclassname">Request.</code><code class="descname">full_url</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-181">传递给构造函数的原始URL。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-182"><span class="versionmodified">在版本3.4中更改</span></span></p></div><p><span class="yiyi-st" id="yiyi-183">Request.full_url是一个具有setter，getter和deleter的属性。</span><span class="yiyi-st" id="yiyi-184">获取<a class="reference internal" href="#urllib.request.Request.full_url" title="urllib.request.Request.full_url"><code class="xref py py-attr docutils literal"><span class="pre">full_url</span></code></a>返回带有片段的原始请求URL（如果存在）。</span></p></dd></dl><dl class="attribute"><dt id="urllib.request.Request.type"><span class="yiyi-st" id="yiyi-185"> <code class="descclassname">Request.</code><code class="descname">type</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-186">URI方案。</span></p></dd></dl><dl class="attribute"><dt id="urllib.request.Request.host"><span class="yiyi-st" id="yiyi-187"> <code class="descclassname">Request.</code><code class="descname">host</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-188">URI权限（通常是主机），但也可能包含由冒号分隔的端口。</span></p></dd></dl><dl class="attribute"><dt id="urllib.request.Request.origin_req_host"><span class="yiyi-st" id="yiyi-189"> <code class="descclassname">Request.</code><code class="descname">origin_req_host</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-190">请求的原始主机，不带端口。</span></p></dd></dl><dl class="attribute"><dt id="urllib.request.Request.selector"><span class="yiyi-st" id="yiyi-191"> <code class="descclassname">Request.</code><code class="descname">selector</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-192">URI路径。</span><span class="yiyi-st" id="yiyi-193">如果<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>使用代理，则选择器将是传递给代理的完整URL。</span></p></dd></dl><dl class="attribute"><dt id="urllib.request.Request.data"><span class="yiyi-st" id="yiyi-194"> <code class="descclassname">Request.</code><code class="descname">data</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-195">请求的实体主体，如果未指定，则返回None。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-196"><span class="versionmodified">版本3.4中的更改：</span>现在，<a class="reference internal" href="#urllib.request.Request.data" title="urllib.request.Request.data"><code class="xref py py-attr docutils literal"><span class="pre">Request.data</span></code></a>的值现在会删除“Content-Length”标头，前提是它已被设置或计算。</span></p></div></dd></dl><dl class="attribute"><dt id="urllib.request.Request.unverifiable"><span class="yiyi-st" id="yiyi-197"> <code class="descclassname">Request.</code><code class="descname">unverifiable</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-198">布尔值，表示请求是否是RFC 2965定义的不可验证的。</span></p></dd></dl><dl class="attribute"><dt id="urllib.request.Request.method"><span class="yiyi-st" id="yiyi-199"> <code class="descclassname">Request.</code><code class="descname">method</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-200">要使用的HTTP请求方法。</span><span class="yiyi-st" id="yiyi-201">默认情况下，其值为<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>，这意味着<a class="reference internal" href="#urllib.request.Request.get_method" title="urllib.request.Request.get_method"><code class="xref py py-meth docutils literal"><span class="pre">get_method()</span></code></a>将对要使用的方法执行其正常计算。</span><span class="yiyi-st" id="yiyi-202">可以通过在<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">请求</span></code></a>子类中的类级别设置默认值来设置其值（从而覆盖<a class="reference internal" href="#urllib.request.Request.get_method" title="urllib.request.Request.get_method"><code class="xref py py-meth docutils literal"><span class="pre">get_method()</span></code></a>中的默认计算）通过<em>方法</em>参数将值传递给<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>构造函数。</span></p><div class="versionadded"><p><span class="yiyi-st" id="yiyi-203"><span class="versionmodified">版本3.3中的新功能。</span></span></p></div><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-204"><span class="versionmodified">Changed in version 3.4: </span>A default value can now be set in subclasses; previously it could only be set via the constructor argument.</span></p></div></dd></dl><dl class="method"><dt id="urllib.request.Request.get_method"><span class="yiyi-st" id="yiyi-205"> <code class="descclassname">Request.</code><code class="descname">get_method</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-206">返回一个指示HTTP请求方法的字符串。</span><span class="yiyi-st" id="yiyi-207">如果<a class="reference internal" href="#urllib.request.Request.method" title="urllib.request.Request.method"><code class="xref py py-attr docutils literal"><span class="pre">Request.method</span></code></a>不是<code class="docutils literal"><span class="pre">None</span></code>，则返回其值，否则返回<code class="docutils literal"><span class="pre">'GET'</span></code>，如果<a class="reference internal" href="#urllib.request.Request.data" title="urllib.request.Request.data"><code class="xref py py-attr docutils literal"><span class="pre">Request.data</span></code></a>为<code class="docutils literal"><span class="pre">None</span></code>或<code class="docutils literal"><span class="pre">'POST'</span></code>（如果不是）。</span><span class="yiyi-st" id="yiyi-208">这只对HTTP请求有意义。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-209"><span class="versionmodified">在版本3.3中更改：</span> get_method现在查看<a class="reference internal" href="#urllib.request.Request.method" title="urllib.request.Request.method"><code class="xref py py-attr docutils literal"><span class="pre">Request.method</span></code></a>的值。</span></p></div></dd></dl><dl class="method"><dt id="urllib.request.Request.add_header"><span class="yiyi-st" id="yiyi-210"> <code class="descclassname">Request.</code><code class="descname">add_header</code><span class="sig-paren">(</span><em>key</em>, <em>val</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-211">向请求中添加另一个标头。</span><span class="yiyi-st" id="yiyi-212">除了HTTP处理程序之外，所有处理程序当前都会忽略标头，并将其添加到发送到服务器的标头列表中。</span><span class="yiyi-st" id="yiyi-213">注意，不能有多个具有相同名称的标题，并且在<em>键</em>发生冲突的情况下，稍后的调用将覆盖以前的调用。</span><span class="yiyi-st" id="yiyi-214">目前，这不是HTTP功能的丢失，因为当使用多次时具有含义的所有head具有（head特定的）仅使用一个报头获得相同功能的方式。</span></p></dd></dl><dl class="method"><dt id="urllib.request.Request.add_unredirected_header"><span class="yiyi-st" id="yiyi-215"> <code class="descclassname">Request.</code><code class="descname">add_unredirected_header</code><span class="sig-paren">(</span><em>key</em>, <em>header</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-216">添加不会添加到重定向请求的标头。</span></p></dd></dl><dl class="method"><dt id="urllib.request.Request.has_header"><span class="yiyi-st" id="yiyi-217"> <code class="descclassname">Request.</code><code class="descname">has_header</code><span class="sig-paren">(</span><em>header</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-218">返回实例是否具有指定的头（同时检查常规和未重定向）。</span></p></dd></dl><dl class="method"><dt id="urllib.request.Request.remove_header"><span class="yiyi-st" id="yiyi-219"> <code class="descclassname">Request.</code><code class="descname">remove_header</code><span class="sig-paren">(</span><em>header</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-220">从请求实例中删除已命名的头文件（来自常规和未重定向的头文件）。</span></p><div class="versionadded"><p><span class="yiyi-st" id="yiyi-221"><span class="versionmodified">版本3.4中的新功能。</span></span></p></div></dd></dl><dl class="method"><dt id="urllib.request.Request.get_full_url"><span class="yiyi-st" id="yiyi-222"> <code class="descclassname">Request.</code><code class="descname">get_full_url</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-223">返回构造函数中给定的URL。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-224"><span class="versionmodified">在版本3.4中更改</span></span></p></div><p><span class="yiyi-st" id="yiyi-225">返回<a class="reference internal" href="#urllib.request.Request.full_url" title="urllib.request.Request.full_url"><code class="xref py py-attr docutils literal"><span class="pre">Request.full_url</span></code></a></span></p></dd></dl><dl class="method"><dt id="urllib.request.Request.set_proxy"><span class="yiyi-st" id="yiyi-226"> <code class="descclassname">Request.</code><code class="descname">set_proxy</code><span class="sig-paren">(</span><em>host</em>, <em>type</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-227">通过连接到代理服务器来准备请求。</span><span class="yiyi-st" id="yiyi-228"><em>host</em>和<em>类型</em>将替换实例的实例，实例的选择器将是构造函数中给出的原始URL。</span></p></dd></dl><dl class="method"><dt id="urllib.request.Request.get_header"><span class="yiyi-st" id="yiyi-229"> <code class="descclassname">Request.</code><code class="descname">get_header</code><span class="sig-paren">(</span><em>header_name</em>, <em>default=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-230">返回给定头的值。</span><span class="yiyi-st" id="yiyi-231">如果头不存在，返回默认值。</span></p></dd></dl><dl class="method"><dt id="urllib.request.Request.header_items"><span class="yiyi-st" id="yiyi-232"> <code class="descclassname">Request.</code><code class="descname">header_items</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-233">返回请求标头的元组列表（header_name，header_value）。</span></p></dd></dl><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-234"><span class="versionmodified">版本3.4中已更改：</span>自3.3版本以来已弃用的请求方法add_data，has_data，get_data，get_type，get_host，get_selector，get_origin_req_host和is_unverifiable。</span></p></div></div><div class="section" id="openerdirector-objects"><h2><span class="yiyi-st" id="yiyi-235">21.6.2. </span><span class="yiyi-st" id="yiyi-236">OpenerDirector对象</span></h2><p><span class="yiyi-st" id="yiyi-237"><a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a> instances have the following methods:</span></p><dl class="method"><dt id="urllib.request.OpenerDirector.add_handler"><span class="yiyi-st" id="yiyi-238"> <code class="descclassname">OpenerDirector.</code><code class="descname">add_handler</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-239"><em>handler</em>应该是<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>的一个实例。</span><span class="yiyi-st" id="yiyi-240">搜索以下方法，并将其添加到可能的链中（请注意，HTTP错误是一种特殊情况）。</span></p><ul class="simple"><li><span class="yiyi-st" id="yiyi-241"><code class="xref py py-meth docutils literal"><span class="pre">protocol_open()</span></code>  - 表示处理程序知道如何打开<em>协议</em> URL。</span></li><li><span class="yiyi-st" id="yiyi-242"><code class="xref py py-meth docutils literal"><span class="pre">http_error_type()</span></code>  - 表示处理程序知道如何使用HTTP错误代码<em>键入</em>来处理HTTP错误。</span></li><li><span class="yiyi-st" id="yiyi-243"><code class="xref py py-meth docutils literal"><span class="pre">protocol_error()</span></code>  - 表示处理程序知道如何处理来自（非<code class="docutils literal"><span class="pre">http</span></code>）<em>协议</em>的错误。</span></li><li><span class="yiyi-st" id="yiyi-244"><code class="xref py py-meth docutils literal"><span class="pre">protocol_request()</span></code>  - 表示处理程序知道如何预处理<em>协议</em>请求。</span></li><li><span class="yiyi-st" id="yiyi-245"><code class="xref py py-meth docutils literal"><span class="pre">protocol_response()</span></code>  - 表示处理程序知道如何后处理<em>协议</em>响应。</span></li></ul></dd></dl><dl class="method"><dt id="urllib.request.OpenerDirector.open"><span class="yiyi-st" id="yiyi-246"> <code class="descclassname">OpenerDirector.</code><code class="descname">open</code><span class="sig-paren">(</span><em>url</em>, <em>data=None</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-247">打开给定的<em>url</em>（可以是请求对象或字符串），可选地传递给定的<em>数据</em>。</span><span class="yiyi-st" id="yiyi-248">Arguments, return values and exceptions raised are the same as those of <a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a> (which simply calls the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal"><span class="pre">open()</span></code></a> method on the currently installed global <a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>). </span><span class="yiyi-st" id="yiyi-249">可选的<em>timeout</em>参数指定阻塞操作（如连接尝试）的超时（以秒为单位）（如果未指定，将使用全局默认超时设置）。</span><span class="yiyi-st" id="yiyi-250">超时功能实际上仅适用于HTTP，HTTPS和FTP连接）。</span></p></dd></dl><dl class="method"><dt id="urllib.request.OpenerDirector.error"><span class="yiyi-st" id="yiyi-251"> <code class="descclassname">OpenerDirector.</code><code class="descname">error</code><span class="sig-paren">(</span><em>proto</em>, <em>*args</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-252">处理给定协议的错误。</span><span class="yiyi-st" id="yiyi-253">这将使用给定的参数（特定于协议）调用给定协议的注册错误处理程序。</span><span class="yiyi-st" id="yiyi-254">HTTP协议是一种特殊情况，它使用HTTP响应代码来确定特定的错误处理程序；请参阅处理程序类的<code class="xref py py-meth docutils literal"><span class="pre">http_error_*()</span></code>方法。</span></p><p><span class="yiyi-st" id="yiyi-255">返回的值和异常与<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>相同。</span></p></dd></dl><p><span class="yiyi-st" id="yiyi-256">OpenerDirector对象分三个阶段打开URL：</span></p><p><span class="yiyi-st" id="yiyi-257">在每个阶段中调用这些方法的顺序是通过对处理程序实例进行排序来确定的。</span></p><ol class="arabic"><li><p class="first"><span class="yiyi-st" id="yiyi-258">每个使用名为<code class="xref py py-meth docutils literal"><span class="pre">protocol_request()</span></code>的方法的处理程序都会调用该方法来预处理请求。</span></p></li><li><p class="first"><span class="yiyi-st" id="yiyi-259">调用带有名为<code class="xref py py-meth docutils literal"><span class="pre">protocol_open()</span></code>的方法处理请求。</span><span class="yiyi-st" id="yiyi-260">当处理程序返回非<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>值（例如</span><span class="yiyi-st" id="yiyi-261">一个响应），或引发一个异常（通常是<a class="reference internal" href="urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal"><span class="pre">URLError</span></code></a>）时，这个阶段结束。</span><span class="yiyi-st" id="yiyi-262">允许异常传播。</span></p><p><span class="yiyi-st" id="yiyi-263">实际上，首先对名为<code class="xref py py-meth docutils literal"><span class="pre">default_open()</span></code>的方法尝试了上述算法。</span><span class="yiyi-st" id="yiyi-264">如果所有这些方法都返回<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>，则对于名为<code class="xref py py-meth docutils literal"><span class="pre">protocol_open()</span></code>的方法重复该算法。</span><span class="yiyi-st" id="yiyi-265">如果所有这些方法都返回<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a>，则对于名为<code class="xref py py-meth docutils literal"><span class="pre">unknown_open()</span></code>的方法重复该算法。</span></p><p><span class="yiyi-st" id="yiyi-266">请注意，这些方法的实现可能涉及父对象<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>实例的<a class="reference internal" href="#urllib.request.OpenerDirector.open" title="urllib.request.OpenerDirector.open"><code class="xref py py-meth docutils literal"><span class="pre">open()</span></code></a>和<a class="reference internal" href="#urllib.request.OpenerDirector.error" title="urllib.request.OpenerDirector.error"><code class="xref py py-meth docutils literal"><span class="pre">error()</span></code></a>方法的调用。</span></p></li><li><p class="first"><span class="yiyi-st" id="yiyi-267">每个使用名为<code class="xref py py-meth docutils literal"><span class="pre">protocol_response()</span></code>的方法的处理程序都会调用该方法来后处理响应。</span></p></li></ol></div><div class="section" id="basehandler-objects"><h2><span class="yiyi-st" id="yiyi-268">21.6.3. </span><span class="yiyi-st" id="yiyi-269">BaseHandler对象</span></h2><p><span class="yiyi-st" id="yiyi-270"><a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a> objects provide a couple of methods that are directly useful, and others that are meant to be used by derived classes. </span><span class="yiyi-st" id="yiyi-271">这些用于直接使用：</span></p><dl class="method"><dt id="urllib.request.BaseHandler.add_parent"><span class="yiyi-st" id="yiyi-272"> <code class="descclassname">BaseHandler.</code><code class="descname">add_parent</code><span class="sig-paren">(</span><em>director</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-273">添加导演作为父项。</span></p></dd></dl><dl class="method"><dt id="urllib.request.BaseHandler.close"><span class="yiyi-st" id="yiyi-274"> <code class="descclassname">BaseHandler.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-275">删除任何父母。</span></p></dd></dl><p><span class="yiyi-st" id="yiyi-276">以下属性和方法只能由派生自<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>的类使用。</span></p><div class="admonition note"><p class="first admonition-title"><span class="yiyi-st" id="yiyi-277">注意</span></p><p class="last"><span class="yiyi-st" id="yiyi-278">该惯例已被采用，定义<code class="xref py py-meth docutils literal"><span class="pre">protocol_request()</span></code>或<code class="xref py py-meth docutils literal"><span class="pre">protocol_response()</span></code>方法的子类被命名为<code class="xref py py-class docutils literal"><span class="pre">*Processor</span></code>所有其他人都被命名为<code class="xref py py-class docutils literal"><span class="pre">*Handler</span></code>。</span></p></div><dl class="attribute"><dt id="urllib.request.BaseHandler.parent"><span class="yiyi-st" id="yiyi-279"> <code class="descclassname">BaseHandler.</code><code class="descname">parent</code></span></dt><dd><p><span class="yiyi-st" id="yiyi-280">一个有效的<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>，可用于使用其他协议打开或处理错误。</span></p></dd></dl><dl class="method"><dt id="urllib.request.BaseHandler.default_open"><span class="yiyi-st" id="yiyi-281"> <code class="descclassname">BaseHandler.</code><code class="descname">default_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-282">这个方法<em>不是</em>在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中定义的，但是如果要捕获所有URL，子类应该定义它。</span></p><p><span class="yiyi-st" id="yiyi-283">此方法（如果已实施）将由父<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>调用。</span><span class="yiyi-st" id="yiyi-284">它应该返回一个文件类对象，如<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>或<code class="docutils literal"><span class="pre">None</span></code>的<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal"><span class="pre">open()</span></code></a>的返回值所述。</span><span class="yiyi-st" id="yiyi-285">它应该引发<a class="reference internal" href="urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal"><span class="pre">URLError</span></code></a>，除非发生真正的例外情况（例如，<a class="reference internal" href="exceptions.html#MemoryError" title="MemoryError"><code class="xref py py-exc docutils literal"><span class="pre">MemoryError</span></code></a>不应映射到<code class="xref py py-exc docutils literal"><span class="pre">URLError</span></code>）。</span></p><p><span class="yiyi-st" id="yiyi-286">此方法将在任何协议特定的打开方法之前调用。</span></p></dd></dl><dl class="method"><dt><span class="yiyi-st" id="yiyi-287"> <code class="descclassname">BaseHandler.</code><code class="descname">protocol_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-288">这个方法在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中定义<em>not</em>，但是如果要使用给定协议处理URL，子类应该定义它。</span></p><p><span class="yiyi-st" id="yiyi-289">此方法（如果已定义）将由父<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>调用。</span><span class="yiyi-st" id="yiyi-290">返回值应该与<a class="reference internal" href="#urllib.request.BaseHandler.default_open" title="urllib.request.BaseHandler.default_open"><code class="xref py py-meth docutils literal"><span class="pre">default_open()</span></code></a>相同。</span></p></dd></dl><dl class="method"><dt id="urllib.request.BaseHandler.unknown_open"><span class="yiyi-st" id="yiyi-291"> <code class="descclassname">BaseHandler.</code><code class="descname">unknown_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-292">在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中定义<em>not</em>，但如果要捕获所有没有特定注册处理程序的URL来打开它，子类应该定义它。</span></p><p><span class="yiyi-st" id="yiyi-293">This method, if implemented, will be called by the <a class="reference internal" href="#urllib.request.BaseHandler.parent" title="urllib.request.BaseHandler.parent"><code class="xref py py-attr docutils literal"><span class="pre">parent</span></code></a> <a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>. </span><span class="yiyi-st" id="yiyi-294">返回值应该与<a class="reference internal" href="#urllib.request.BaseHandler.default_open" title="urllib.request.BaseHandler.default_open"><code class="xref py py-meth docutils literal"><span class="pre">default_open()</span></code></a>相同。</span></p></dd></dl><dl class="method"><dt id="urllib.request.BaseHandler.http_error_default"><span class="yiyi-st" id="yiyi-295"> <code class="descclassname">BaseHandler.</code><code class="descname">http_error_default</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-296">这个方法在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中定义<em>not</em>，但是如果它们打算提供一个catch-all来处理未处理的HTTP错误，则子类应该覆盖它。</span><span class="yiyi-st" id="yiyi-297">它会由<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>自动调用以获取错误，通常不应在其他情况下调用。</span></p><p><span class="yiyi-st" id="yiyi-298"><em>req</em> will be a <a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a> object, <em>fp</em> will be a file-like object with the HTTP error body, <em>code</em> will be the three-digit code of the error, <em>msg</em> will be the user-visible explanation of the code and <em>hdrs</em> will be a mapping object with the headers of the error.</span></p><p><span class="yiyi-st" id="yiyi-299">返回值和异常应与<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>相同。</span></p></dd></dl><dl class="method"><dt id="urllib.request.BaseHandler.http_error_nnn"><span class="yiyi-st" id="yiyi-300"> <code class="descclassname">BaseHandler.</code><code class="descname">http_error_nnn</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-301"><em>nnn</em>应该是一个三位数的HTTP错误代码。</span><span class="yiyi-st" id="yiyi-302">这个方法在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中也没有定义，但是如果存在的话，在一个子类的实例中，当发生带有代码<em>nnn</em>的HTTP错误时，它将被调用。</span></p><p><span class="yiyi-st" id="yiyi-303">子类应该重写此方法来处理特定的HTTP错误。</span></p><p><span class="yiyi-st" id="yiyi-304">所引发的参数，返回值和异常应该与<a class="reference internal" href="#urllib.request.BaseHandler.http_error_default" title="urllib.request.BaseHandler.http_error_default"><code class="xref py py-meth docutils literal"><span class="pre">http_error_default()</span></code></a>相同。</span></p></dd></dl><dl class="method"><dt><span class="yiyi-st" id="yiyi-305"> <code class="descclassname">BaseHandler.</code><code class="descname">protocol_request</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-306">这个方法在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中定义<em>not</em>，但如果要预处理给定协议的请求，子类应该定义它。</span></p><p><span class="yiyi-st" id="yiyi-307">此方法（如果已定义）将由父<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>调用。</span><span class="yiyi-st" id="yiyi-308"><em>req</em>将是一个<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>对象。</span><span class="yiyi-st" id="yiyi-309">返回值应该是一个<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>对象。</span></p></dd></dl><dl class="method"><dt><span class="yiyi-st" id="yiyi-310"> <code class="descclassname">BaseHandler.</code><code class="descname">protocol_response</code><span class="sig-paren">(</span><em>req</em>, <em>response</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-311">这个方法在<a class="reference internal" href="#urllib.request.BaseHandler" title="urllib.request.BaseHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseHandler</span></code></a>中定义<em>not</em>，但是如果子类想要后处理给定协议的响应，应该定义它。</span></p><p><span class="yiyi-st" id="yiyi-312">此方法（如果已定义）将由父<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>调用。</span><span class="yiyi-st" id="yiyi-313"><em>req</em>将是一个<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>对象。</span><span class="yiyi-st" id="yiyi-314"><em>响应</em>将是一个实现与<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>的返回值相同接口的对象。</span><span class="yiyi-st" id="yiyi-315">返回值应该实现与<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>的返回值相同的接口。</span></p></dd></dl></div><div class="section" id="httpredirecthandler-objects"><h2><span class="yiyi-st" id="yiyi-316">21.6.4. </span><span class="yiyi-st" id="yiyi-317">HTTPRedirectHandler对象</span></h2><div class="admonition note"><p class="first admonition-title"><span class="yiyi-st" id="yiyi-318">注意</span></p><p><span class="yiyi-st" id="yiyi-319">某些HTTP重定向需要来自此模块的客户端代码的操作。</span><span class="yiyi-st" id="yiyi-320">如果是这种情况，则引发<a class="reference internal" href="urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal"><span class="pre">HTTPError</span></code></a>。</span><span class="yiyi-st" id="yiyi-321">有关各种重定向代码的准确含义的详细信息，请参阅<span class="target" id="index-4"></span> <a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>。</span></p><p class="last"><span class="yiyi-st" id="yiyi-322">如果HTTPRedirectHandler显示的重定向URL不是HTTP，HTTPS或FTP URL，则会引发<code class="xref py py-class docutils literal"><span class="pre">HTTPError</span></code>异常作为安全考虑。</span></p></div><dl class="method"><dt id="urllib.request.HTTPRedirectHandler.redirect_request"><span class="yiyi-st" id="yiyi-323"> <code class="descclassname">HTTPRedirectHandler.</code><code class="descname">redirect_request</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em>, <em>newurl</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-324">响应重定向，返回<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>或<code class="docutils literal"><span class="pre">None</span></code>。</span><span class="yiyi-st" id="yiyi-325">当从服务器收到重定向时，这由<code class="xref py py-meth docutils literal"><span class="pre">http_error_30*()</span></code>方法的默认实现调用。</span><span class="yiyi-st" id="yiyi-326">如果发生重定向，则返回一个新的<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>以允许<code class="xref py py-meth docutils literal"><span class="pre">http_error_30*()</span></code>执行重定向到<em>newurl</em>。</span><span class="yiyi-st" id="yiyi-327">否则，如果没有其他处理程序尝试处理此URL，则引发<a class="reference internal" href="urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal"><span class="pre">HTTPError</span></code></a>；如果不能，则返回<code class="docutils literal"><span class="pre">None</span></code>。</span></p><div class="admonition note"><p class="first admonition-title"><span class="yiyi-st" id="yiyi-328">注意</span></p><p class="last"><span class="yiyi-st" id="yiyi-329">此方法的默认实现不严格遵循<span class="target" id="index-5"></span> <a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>，其中说明对<code class="docutils literal"><span class="pre">POST</span></code>请求的301和302响应不得自动重定向用户确认。</span><span class="yiyi-st" id="yiyi-330">实际上，浏览器确实允许自动重定向这些响应，将POST更改为<code class="docutils literal"><span class="pre">GET</span></code>，并且默认实现将重现此行为。</span></p></div></dd></dl><dl class="method"><dt id="urllib.request.HTTPRedirectHandler.http_error_301"><span class="yiyi-st" id="yiyi-331"> <code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_301</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-332">重定向到<code class="docutils literal"><span class="pre">Location:</span></code>或<code class="docutils literal"><span class="pre">URI:</span></code>网址。</span><span class="yiyi-st" id="yiyi-333">当获得HTTP'永久移动'响应时，此方法由父<a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a>调用。</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPRedirectHandler.http_error_302"><span class="yiyi-st" id="yiyi-334"> <code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_302</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-335">与<a class="reference internal" href="#urllib.request.HTTPRedirectHandler.http_error_301" title="urllib.request.HTTPRedirectHandler.http_error_301"><code class="xref py py-meth docutils literal"><span class="pre">http_error_301()</span></code></a>相同，但要求“找到”响应。</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPRedirectHandler.http_error_303"><span class="yiyi-st" id="yiyi-336"> <code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_303</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-337">与<a class="reference internal" href="#urllib.request.HTTPRedirectHandler.http_error_301" title="urllib.request.HTTPRedirectHandler.http_error_301"><code class="xref py py-meth docutils literal"><span class="pre">http_error_301()</span></code></a>相同，但要求“看到其他”响应。</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPRedirectHandler.http_error_307"><span class="yiyi-st" id="yiyi-338"> <code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_307</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-339">与<a class="reference internal" href="#urllib.request.HTTPRedirectHandler.http_error_301" title="urllib.request.HTTPRedirectHandler.http_error_301"><code class="xref py py-meth docutils literal"><span class="pre">http_error_301()</span></code></a>相同，但要求“临时重定向”响应。</span></p></dd></dl></div><div class="section" id="httpcookieprocessor-objects"><h2><span class="yiyi-st" id="yiyi-340">21.6.5. </span><span class="yiyi-st" id="yiyi-341">HTTPCookieProcessor对象</span></h2><p><span class="yiyi-st" id="yiyi-342"><a class="reference internal" href="#urllib.request.HTTPCookieProcessor" title="urllib.request.HTTPCookieProcessor"><code class="xref py py-class docutils literal"><span class="pre">HTTPCookieProcessor</span></code></a>实例有一个属性：</span></p><dl class="attribute"><dt id="urllib.request.HTTPCookieProcessor.cookiejar"><span class="yiyi-st" id="yiyi-343"><code class="descclassname"> HTTPCookieProcessor。 T0&gt; <code class="descname"> cookiejar  T1&gt; </code></code></span></dt><dd><p><span class="yiyi-st" id="yiyi-344">存储cookie的<a class="reference internal" href="http.cookiejar.html#http.cookiejar.CookieJar" title="http.cookiejar.CookieJar"><code class="xref py py-class docutils literal"><span class="pre">http.cookiejar.CookieJar</span></code></a>。</span></p></dd></dl></div><div class="section" id="proxyhandler-objects"><h2><span class="yiyi-st" id="yiyi-345">21.6.6. </span><span class="yiyi-st" id="yiyi-346">ProxyHandler对象</span></h2><dl class="method"><dt><span class="yiyi-st" id="yiyi-347"> <code class="descclassname">ProxyHandler.</code><code class="descname">protocol_open</code><span class="sig-paren">(</span><em>request</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-348">对于每个<em>协议</em>，<a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler</span></code></a>都有一个方法<code class="xref py py-meth docutils literal"><span class="pre">protocol_open()</span></code>，它在<em>代理</em>构造函数。</span><span class="yiyi-st" id="yiyi-349">该方法将通过调用<code class="docutils literal"><span class="pre">request.set_proxy()</span></code>修改通过代理的请求，并调用链中的下一个处理程序以实际执行协议。</span></p></dd></dl></div><div class="section" id="httppasswordmgr-objects"><h2><span class="yiyi-st" id="yiyi-350">21.6.7. </span><span class="yiyi-st" id="yiyi-351">HTTPPasswordMgr对象</span></h2><p><span class="yiyi-st" id="yiyi-352">这些方法在<a class="reference internal" href="#urllib.request.HTTPPasswordMgr" title="urllib.request.HTTPPasswordMgr"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgr</span></code></a>和<a class="reference internal" href="#urllib.request.HTTPPasswordMgrWithDefaultRealm" title="urllib.request.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a>对象上可用。</span></p><dl class="method"><dt id="urllib.request.HTTPPasswordMgr.add_password"><span class="yiyi-st" id="yiyi-353"> <code class="descclassname">HTTPPasswordMgr.</code><code class="descname">add_password</code><span class="sig-paren">(</span><em>realm</em>, <em>uri</em>, <em>user</em>, <em>passwd</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-354"><em>uri</em> can be either a single URI, or a sequence of URIs. </span><span class="yiyi-st" id="yiyi-355"><em>realm</em>，<em>user</em>和<em>passwd</em>必须是字符串。</span><span class="yiyi-st" id="yiyi-356">这导致<em>realm</em>和超级URI认证时<code class="docutils literal"><span class="pre">（user，</span> <span class="pre">passwd）</span></code>用作认证令牌给出了任何给定的URI。</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPPasswordMgr.find_user_password"><span class="yiyi-st" id="yiyi-357"> <code class="descclassname">HTTPPasswordMgr.</code><code class="descname">find_user_password</code><span class="sig-paren">(</span><em>realm</em>, <em>authuri</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-358">获取给定领域和URI的用户/密码（如果有的话）。</span><span class="yiyi-st" id="yiyi-359">如果没有匹配的用户/密码，该方法将返回<code class="docutils literal"><span class="pre">（None，</span> <span class="pre">None）</span></code>。</span></p><p><span class="yiyi-st" id="yiyi-360">对于<a class="reference internal" href="#urllib.request.HTTPPasswordMgrWithDefaultRealm" title="urllib.request.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a>对象，如果给定的<em>领域</em>没有匹配的用户/密码，则搜索领域<code class="docutils literal"><span class="pre">None</span></code>。</span></p></dd></dl></div><div class="section" id="httppasswordmgrwithpriorauth-objects"><h2><span class="yiyi-st" id="yiyi-361">21.6.8. </span><span class="yiyi-st" id="yiyi-362">HTTPPasswordMgrWithPriorAuth对象</span></h2><p><span class="yiyi-st" id="yiyi-363">此密码管理器扩展<a class="reference internal" href="#urllib.request.HTTPPasswordMgrWithDefaultRealm" title="urllib.request.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a>以支持始终发送验证凭证的跟踪URI。</span></p><dl class="method"><dt id="urllib.request.HTTPPasswordMgrWithPriorAuth.add_password"><span class="yiyi-st" id="yiyi-364"> <code class="descclassname">HTTPPasswordMgrWithPriorAuth.</code><code class="descname">add_password</code><span class="sig-paren">(</span><em>realm</em>, <em>uri</em>, <em>user</em>, <em>passwd</em>, <em>is_authenticated=False</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-365"><em>realm</em>，<em>uri</em>，<em>user</em>，<em>passwd</em>与<a class="reference internal" href="#urllib.request.HTTPPasswordMgr.add_password" title="urllib.request.HTTPPasswordMgr.add_password"><code class="xref py py-meth docutils literal"><span class="pre">HTTPPasswordMgr.add_password()</span></code></a> 。</span><span class="yiyi-st" id="yiyi-366"><em>is_authenticated</em>设置给定URI或URI列表的<code class="docutils literal"><span class="pre">is_authenticated</span></code>标志的初始值。</span><span class="yiyi-st" id="yiyi-367">如果<em>is_authenticated</em>被指定为<code class="docutils literal"><span class="pre">True</span></code>，则<em>realm</em>被忽略。</span></p></dd></dl><dl class="method"><dt><span class="yiyi-st" id="yiyi-368"> <code class="descclassname">HTTPPasswordMgr.</code><code class="descname">find_user_password</code><span class="sig-paren">(</span><em>realm</em>, <em>authuri</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-369">与<a class="reference internal" href="#urllib.request.HTTPPasswordMgrWithDefaultRealm" title="urllib.request.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a>对象相同</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPPasswordMgrWithPriorAuth.update_authenticated"><span class="yiyi-st" id="yiyi-370"> <code class="descclassname">HTTPPasswordMgrWithPriorAuth.</code><code class="descname">update_authenticated</code><span class="sig-paren">(</span><em>self</em>, <em>uri</em>, <em>is_authenticated=False</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-371">更新给定<em>uri</em>或URI列表的<code class="docutils literal"><span class="pre">is_authenticated</span></code>标志。</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPPasswordMgrWithPriorAuth.is_authenticated"><span class="yiyi-st" id="yiyi-372"> <code class="descclassname">HTTPPasswordMgrWithPriorAuth.</code><code class="descname">is_authenticated</code><span class="sig-paren">(</span><em>self</em>, <em>authuri</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-373">返回给定URI的<code class="docutils literal"><span class="pre">is_authenticated</span></code>标志的当前状态。</span></p></dd></dl></div><div class="section" id="abstractbasicauthhandler-objects"><h2><span class="yiyi-st" id="yiyi-374">21.6.9. </span><span class="yiyi-st" id="yiyi-375">AbstractBasicAuthHandler对象</span></h2><dl class="method"><dt id="urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed"><span class="yiyi-st" id="yiyi-376"> <code class="descclassname">AbstractBasicAuthHandler.</code><code class="descname">http_error_auth_reqed</code><span class="sig-paren">(</span><em>authreq</em>, <em>host</em>, <em>req</em>, <em>headers</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-377">通过获取用户/密码对来处理认证请求，然后重新尝试请求。</span><span class="yiyi-st" id="yiyi-378"><em>authreq</em>应该是请求中包含领域信息的标题名称，<em>host</em>指定要验证的URL和路径，<em>req t2&gt;应该是（失败的）<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>对象，并且<em>标头</em>应该是错误标头。</em></span></p><p><span class="yiyi-st" id="yiyi-379"><em>host</em>是权威（例如，</span><span class="yiyi-st" id="yiyi-380"><code class="docutils literal"><span class="pre">"python.org"</span></code>）或包含授权组件的URL（例如，</span><span class="yiyi-st" id="yiyi-381"><code class="docutils literal"><span class="pre">"http://python.org/"</span></code></span><span class="yiyi-st" id="yiyi-382">In either case, the authority must not contain a userinfo component (so, <code class="docutils literal"><span class="pre">"python.org"</span></code> and <code class="docutils literal"><span class="pre">"python.org:80"</span></code> are fine, <code class="docutils literal"><span class="pre">"joe:password@python.org"</span></code> is not).</span></p></dd></dl></div><div class="section" id="httpbasicauthhandler-objects"><h2><span class="yiyi-st" id="yiyi-383">21.6.10. </span><span class="yiyi-st" id="yiyi-384">HTTPBasicAuthHandler对象</span></h2><dl class="method"><dt id="urllib.request.HTTPBasicAuthHandler.http_error_401"><span class="yiyi-st" id="yiyi-385"> <code class="descclassname">HTTPBasicAuthHandler.</code><code class="descname">http_error_401</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-386">如果可用，请重新尝试带有认证信息的请求。</span></p></dd></dl></div><div class="section" id="proxybasicauthhandler-objects"><h2><span class="yiyi-st" id="yiyi-387">21.6.11. </span><span class="yiyi-st" id="yiyi-388">ProxyBasicAuthHandler对象</span></h2><dl class="method"><dt id="urllib.request.ProxyBasicAuthHandler.http_error_407"><span class="yiyi-st" id="yiyi-389"> <code class="descclassname">ProxyBasicAuthHandler.</code><code class="descname">http_error_407</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-390">如果可用，请重新尝试带有认证信息的请求。</span></p></dd></dl></div><div class="section" id="abstractdigestauthhandler-objects"><h2><span class="yiyi-st" id="yiyi-391">21.6.12. </span><span class="yiyi-st" id="yiyi-392">AbstractDigestAuthHandler对象</span></h2><dl class="method"><dt id="urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed"><span class="yiyi-st" id="yiyi-393"> <code class="descclassname">AbstractDigestAuthHandler.</code><code class="descname">http_error_auth_reqed</code><span class="sig-paren">(</span><em>authreq</em>, <em>host</em>, <em>req</em>, <em>headers</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-394"><em>authreq</em>应该是请求中包含领域信息的标头名称，<em>host</em>应该是要验证的主机，<em>req  t2 &gt;应该是（失败的）<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>对象，并且<em>标题</em>应该是错误标题。</em></span></p></dd></dl></div><div class="section" id="httpdigestauthhandler-objects"><h2><span class="yiyi-st" id="yiyi-395">21.6.13. </span><span class="yiyi-st" id="yiyi-396">HTTPDigestAuthHandler对象</span></h2><dl class="method"><dt id="urllib.request.HTTPDigestAuthHandler.http_error_401"><span class="yiyi-st" id="yiyi-397"> <code class="descclassname">HTTPDigestAuthHandler.</code><code class="descname">http_error_401</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-398">如果可用，请重新尝试带有认证信息的请求。</span></p></dd></dl></div><div class="section" id="proxydigestauthhandler-objects"><h2><span class="yiyi-st" id="yiyi-399">21.6.14. </span><span class="yiyi-st" id="yiyi-400">ProxyDigestAuthHandler对象</span></h2><dl class="method"><dt id="urllib.request.ProxyDigestAuthHandler.http_error_407"><span class="yiyi-st" id="yiyi-401"> <code class="descclassname">ProxyDigestAuthHandler.</code><code class="descname">http_error_407</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-402">如果可用，请重新尝试带有认证信息的请求。</span></p></dd></dl></div><div class="section" id="httphandler-objects"><h2><span class="yiyi-st" id="yiyi-403">21.6.15. </span><span class="yiyi-st" id="yiyi-404">HTTPHandler对象</span></h2><dl class="method"><dt id="urllib.request.HTTPHandler.http_open"><span class="yiyi-st" id="yiyi-405"> <code class="descclassname">HTTPHandler.</code><code class="descname">http_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-406">根据<code class="docutils literal"><span class="pre">req.has_data()</span></code>发送HTTP请求，该请求可以是GET或POST。</span></p></dd></dl></div><div class="section" id="httpshandler-objects"><h2><span class="yiyi-st" id="yiyi-407">21.6.16. </span><span class="yiyi-st" id="yiyi-408">HTTPSHandler对象</span></h2><dl class="method"><dt id="urllib.request.HTTPSHandler.https_open"><span class="yiyi-st" id="yiyi-409"> <code class="descclassname">HTTPSHandler.</code><code class="descname">https_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-410">根据<code class="docutils literal"><span class="pre">req.has_data()</span></code>发送HTTPS请求，该请求可以是GET或POST。</span></p></dd></dl></div><div class="section" id="filehandler-objects"><h2><span class="yiyi-st" id="yiyi-411">21.6.17. </span><span class="yiyi-st" id="yiyi-412">FileHandler对象</span></h2><dl class="method"><dt id="urllib.request.FileHandler.file_open"><span class="yiyi-st" id="yiyi-413"> <code class="descclassname">FileHandler.</code><code class="descname">file_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-414">如果没有主机名，或者主机名是<code class="docutils literal"><span class="pre">'localhost'</span></code>，则在本地打开文件。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-415"><span class="versionmodified">在版本3.2中更改：</span>此方法仅适用于本地主机名。</span><span class="yiyi-st" id="yiyi-416">当给出远程主机名时，引发<a class="reference internal" href="urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal"><span class="pre">URLError</span></code></a>。</span></p></div></dd></dl></div><div class="section" id="datahandler-objects"><h2><span class="yiyi-st" id="yiyi-417">21.6.18. </span><span class="yiyi-st" id="yiyi-418">DataHandler对象</span></h2><dl class="method"><dt id="urllib.request.DataHandler.data_open"><span class="yiyi-st" id="yiyi-419"> <code class="descclassname">DataHandler.</code><code class="descname">data_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-420">阅读数据网址。</span><span class="yiyi-st" id="yiyi-421">这种URL包含URL本身编码的内容。</span><span class="yiyi-st" id="yiyi-422">数据URL语法在<span class="target" id="index-6"></span> <a class="rfc reference external" href="https://tools.ietf.org/html/rfc2397.html"><strong>RFC 2397</strong></a>中指定。</span><span class="yiyi-st" id="yiyi-423">这个实现忽略了base64编码数据URL中的空白，所以URL可以被包装在任何源文件中。</span><span class="yiyi-st" id="yiyi-424">但即使有些浏览器不介意在base64编码数据URL末尾丢失填充，此实现将在此情况下引发<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal"><span class="pre">ValueError</span></code></a>。</span></p></dd></dl></div><div class="section" id="ftphandler-objects"><h2><span class="yiyi-st" id="yiyi-425">21.6.19. </span><span class="yiyi-st" id="yiyi-426">FTPHandler对象</span></h2><dl class="method"><dt id="urllib.request.FTPHandler.ftp_open"><span class="yiyi-st" id="yiyi-427"> <code class="descclassname">FTPHandler.</code><code class="descname">ftp_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-428">打开由<em>req</em>指示的FTP文件。</span><span class="yiyi-st" id="yiyi-429">登录始终使用空的用户名和密码完成。</span></p></dd></dl></div><div class="section" id="cacheftphandler-objects"><h2><span class="yiyi-st" id="yiyi-430">21.6.20. </span><span class="yiyi-st" id="yiyi-431">CacheFTPHandler对象</span></h2><p><span class="yiyi-st" id="yiyi-432"><a class="reference internal" href="#urllib.request.CacheFTPHandler" title="urllib.request.CacheFTPHandler"><code class="xref py py-class docutils literal"><span class="pre">CacheFTPHandler</span></code></a>对象是<a class="reference internal" href="#urllib.request.FTPHandler" title="urllib.request.FTPHandler"><code class="xref py py-class docutils literal"><span class="pre">FTPHandler</span></code></a>对象，具有以下附加方法：</span></p><dl class="method"><dt id="urllib.request.CacheFTPHandler.setTimeout"><span class="yiyi-st" id="yiyi-433"> <code class="descclassname">CacheFTPHandler.</code><code class="descname">setTimeout</code><span class="sig-paren">(</span><em>t</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-434">将连接超时设置为<em>t</em>秒。</span></p></dd></dl><dl class="method"><dt id="urllib.request.CacheFTPHandler.setMaxConns"><span class="yiyi-st" id="yiyi-435"> <code class="descclassname">CacheFTPHandler.</code><code class="descname">setMaxConns</code><span class="sig-paren">(</span><em>m</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-436">将最大数量的缓存连接设置为<em>m</em>。</span></p></dd></dl></div><div class="section" id="unknownhandler-objects"><h2><span class="yiyi-st" id="yiyi-437">21.6.21. </span><span class="yiyi-st" id="yiyi-438">UnknownHandler对象</span></h2><dl class="method"><dt id="urllib.request.UnknownHandler.unknown_open"><span class="yiyi-st" id="yiyi-439"> <code class="descclassname">UnknownHandler.</code><code class="descname">unknown_open</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-440">引发一个<a class="reference internal" href="urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal"><span class="pre">URLError</span></code></a>异常。</span></p></dd></dl></div><div class="section" id="httperrorprocessor-objects"><h2><span class="yiyi-st" id="yiyi-441">21.6.22. </span><span class="yiyi-st" id="yiyi-442">HTTPErrorProcessor对象</span></h2><dl class="method"><dt id="urllib.request.HTTPErrorProcessor.http_response"><span class="yiyi-st" id="yiyi-443"> <code class="descclassname">HTTPErrorProcessor.</code><code class="descname">http_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-444">处理HTTP错误响应。</span></p><p><span class="yiyi-st" id="yiyi-445">对于200个错误代码，响应对象立即返回。</span></p><p><span class="yiyi-st" id="yiyi-446">对于非200错误代码，这只需通过<a class="reference internal" href="#urllib.request.OpenerDirector.error" title="urllib.request.OpenerDirector.error"><code class="xref py py-meth docutils literal"><span class="pre">OpenerDirector.error()</span></code></a>将作业传递给<code class="xref py py-meth docutils literal"><span class="pre">protocol_error_code()</span></code>处理程序方法。</span><span class="yiyi-st" id="yiyi-447">最终，如果没有其他处理程序处理该错误，那么<a class="reference internal" href="#urllib.request.HTTPDefaultErrorHandler" title="urllib.request.HTTPDefaultErrorHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPDefaultErrorHandler</span></code></a>将引发一个<a class="reference internal" href="urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal"><span class="pre">HTTPError</span></code></a>。</span></p></dd></dl><dl class="method"><dt id="urllib.request.HTTPErrorProcessor.https_response"><span class="yiyi-st" id="yiyi-448"> <code class="descclassname">HTTPErrorProcessor.</code><code class="descname">https_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-449">处理HTTPS错误响应。</span></p><p><span class="yiyi-st" id="yiyi-450">该行为与<a class="reference internal" href="#urllib.request.HTTPErrorProcessor.http_response" title="urllib.request.HTTPErrorProcessor.http_response"><code class="xref py py-meth docutils literal"><span class="pre">http_response()</span></code></a>相同。</span></p></dd></dl></div><div class="section" id="examples"><h2><span class="yiyi-st" id="yiyi-451">21.6.23. </span><span class="yiyi-st" id="yiyi-452">示例 </span></h2><p><span class="yiyi-st" id="yiyi-453">下面的示例中，更多的例子在 <a class="reference internal" href="../howto/urllib2.html#urllib-howto"><span>如何获取互联网资源使用 urllib 软件包</span></a>中列出。</span></p><p><span class="yiyi-st" id="yiyi-454">此示例获取 python.org 主页面，并显示它的开头的 300 个字节。</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://www.python.org/'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">300</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">b'&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"</span>
<span class="go">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;\n\n\n&lt;html</span>
<span class="go">xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;\n\n&lt;head&gt;\n</span>
<span class="go">&lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt;\n</span>
<span class="go">&lt;title&gt;Python Programming '</span>
</code></pre><p><span class="yiyi-st" id="yiyi-455">请注意，urlopen返回一个字节的对象。</span><span class="yiyi-st" id="yiyi-456">这是因为urlopen自动确定从 HTTP 服务器接收的字节流的编码。</span><span class="yiyi-st" id="yiyi-457">一般情况下，程序将解码为字符串返回的字节对象一次确定或猜测的适当的编码。</span></p><p><span class="yiyi-st" id="yiyi-458">下面的 W3C 文档中，<a class="reference external" href="https://www.w3.org/International/O-charset">https://www.w3.org/International/O-charset</a>，列出在其中 (X) HTML 或 XML 文档可能已指定其编码信息的各种方式。</span></p><p><span class="yiyi-st" id="yiyi-459">Python.org 网站使用 <em>utf-8</em> 编码作为其的 meta 标记中指定，我们将使用相同的解码的字节的对象。</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://www.python.org/'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"</span>
<span class="go">"http://www.w3.org/TR/xhtml1/DTD/xhtm</span>
</code></pre><p><span class="yiyi-st" id="yiyi-460">它也是可能而无需使用 <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">上下文管理器</span></a> 方法实现相同的结果。</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://www.python.org/'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">))</span>
<span class="go">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"</span>
<span class="go">"http://www.w3.org/TR/xhtml1/DTD/xhtm</span>
</code></pre><p><span class="yiyi-st" id="yiyi-461">在下面的示例中，我们将数据流发送到CGI的标准，并读取返回给我们的数据。</span><span class="yiyi-st" id="yiyi-462">请注意，此示例将只当 Python 安装支持 SSL。</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="o">=</span><span class="s1">'https://localhost/cgi-bin/test.cgi'</span><span class="p">,</span>
<span class="gp">... </span>                      <span class="n">data</span><span class="o">=</span><span class="n">b</span><span class="s1">'This data is passed to stdin of the CGI'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">Got Data: "This data is passed to stdin of the CGI"</span>
</code></pre><p><span class="yiyi-st" id="yiyi-463">CGI 在上面的示例中使用的示例的代码是︰</span></p><pre><code class="language-python"><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Content-type: text/plain</span><span class="se">\n\n</span><span class="s1">Got Data: "</span><span class="si">%s</span><span class="s1">"'</span> <span class="o">%</span> <span class="n">data</span><span class="p">)</span>
</code></pre><p><span class="yiyi-st" id="yiyi-464">以下是使用<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">请求</span></code></a>执行<code class="docutils literal"><span class="pre">PUT</span></code>请求的示例：</span></p><pre><code class="language-python"><span></span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="n">DATA</span> <span class="o">=</span> <span class="n">b</span><span class="s1">'some data'</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="o">=</span><span class="s1">'http://localhost:8080'</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">DATA</span><span class="p">,</span><span class="n">method</span><span class="o">=</span><span class="s1">'PUT'</span><span class="p">)</span>
<span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">pass</span>
<span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">status</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">reason</span><span class="p">)</span>
</code></pre><p><span class="yiyi-st" id="yiyi-465">使用基本HTTP认证：</span></p><pre><code class="language-python"><span></span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="c1"># Create an OpenerDirector with support for Basic HTTP Authentication...</span>
<span class="n">auth_handler</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">HTTPBasicAuthHandler</span><span class="p">()</span>
<span class="n">auth_handler</span><span class="o">.</span><span class="n">add_password</span><span class="p">(</span><span class="n">realm</span><span class="o">=</span><span class="s1">'PDQ Application'</span><span class="p">,</span>
                          <span class="n">uri</span><span class="o">=</span><span class="s1">'https://mahler:8092/site-updates.py'</span><span class="p">,</span>
                          <span class="n">user</span><span class="o">=</span><span class="s1">'klem'</span><span class="p">,</span>
                          <span class="n">passwd</span><span class="o">=</span><span class="s1">'kadidd!ehopper'</span><span class="p">)</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">auth_handler</span><span class="p">)</span>
<span class="c1"># ...and install it globally so it can be used with urlopen.</span>
<span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">install_opener</span><span class="p">(</span><span class="n">opener</span><span class="p">)</span>
<span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://www.example.com/login.html'</span><span class="p">)</span>
</code></pre><p><span class="yiyi-st" id="yiyi-466"><a class="reference internal" href="#urllib.request.build_opener" title="urllib.request.build_opener"><code class="xref py py-func docutils literal"><span class="pre">build_opener()</span></code></a>默认提供了很多处理程序，包括一个<a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler</span></code></a>。</span><span class="yiyi-st" id="yiyi-467">默认情况下，<a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler</span></code></a>使用名为<code class="docutils literal"><span class="pre">&lt;scheme&gt;_proxy</span></code>的环境变量，其中<code class="docutils literal"><span class="pre">&lt;scheme&gt;</span></code>是涉及的URL方案。</span><span class="yiyi-st" id="yiyi-468">例如，读取<span class="target" id="index-7"></span> <code class="xref std std-envvar docutils literal"><span class="pre">http_proxy</span></code>环境变量以获取HTTP代理的URL。</span></p><p><span class="yiyi-st" id="yiyi-469">This example replaces the default <a class="reference internal" href="#urllib.request.ProxyHandler" title="urllib.request.ProxyHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyHandler</span></code></a> with one that uses programmatically-supplied proxy URLs, and adds proxy authorization support with <a class="reference internal" href="#urllib.request.ProxyBasicAuthHandler" title="urllib.request.ProxyBasicAuthHandler"><code class="xref py py-class docutils literal"><span class="pre">ProxyBasicAuthHandler</span></code></a>.</span></p><pre><code class="language-python"><span></span><span class="n">proxy_handler</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">ProxyHandler</span><span class="p">({</span><span class="s1">'http'</span><span class="p">:</span> <span class="s1">'http://www.example.com:3128/'</span><span class="p">})</span>
<span class="n">proxy_auth_handler</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">ProxyBasicAuthHandler</span><span class="p">()</span>
<span class="n">proxy_auth_handler</span><span class="o">.</span><span class="n">add_password</span><span class="p">(</span><span class="s1">'realm'</span><span class="p">,</span> <span class="s1">'host'</span><span class="p">,</span> <span class="s1">'username'</span><span class="p">,</span> <span class="s1">'password'</span><span class="p">)</span>

<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">proxy_handler</span><span class="p">,</span> <span class="n">proxy_auth_handler</span><span class="p">)</span>
<span class="c1"># This time, rather than install the OpenerDirector, we use it directly:</span>
<span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">'http://www.example.com/login.html'</span><span class="p">)</span>
</code></pre><p><span class="yiyi-st" id="yiyi-470">添加HTTP标头：</span></p><p><span class="yiyi-st" id="yiyi-471">使用<a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">请求</span></code></a>构造函数的<em>头</em>参数，或：</span></p><pre><code class="language-python"><span></span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">'http://www.example.com/'</span><span class="p">)</span>
<span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">'Referer'</span><span class="p">,</span> <span class="s1">'http://www.python.org/'</span><span class="p">)</span>
<span class="c1"># Customize the default User-Agent header value:</span>
<span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">'User-Agent'</span><span class="p">,</span> <span class="s1">'urllib-example/0.1 (Contact: . . .)'</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
</code></pre><p><span class="yiyi-st" id="yiyi-472"><a class="reference internal" href="#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal"><span class="pre">OpenerDirector</span></code></a> automatically adds a <em class="mailheader">User-Agent</em> header to every <a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a>. </span><span class="yiyi-st" id="yiyi-473">更改如下：</span></p><pre><code class="language-python"><span></span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">build_opener</span><span class="p">()</span>
<span class="n">opener</span><span class="o">.</span><span class="n">addheaders</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'User-agent'</span><span class="p">,</span> <span class="s1">'Mozilla/5.0'</span><span class="p">)]</span>
<span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">'http://www.example.com/'</span><span class="p">)</span>
</code></pre><p><span class="yiyi-st" id="yiyi-474">Also, remember that a few standard headers (<em class="mailheader">Content-Length</em>, <em class="mailheader">Content-Type</em> and <em class="mailheader">Host</em>) are added when the <a class="reference internal" href="#urllib.request.Request" title="urllib.request.Request"><code class="xref py py-class docutils literal"><span class="pre">Request</span></code></a> is passed to <a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a> (or <a class="reference internal" href="#urllib.request.OpenerDirector.open" title="urllib.request.OpenerDirector.open"><code class="xref py py-meth docutils literal"><span class="pre">OpenerDirector.open()</span></code></a>).</span></p><p id="urllib-examples"><span class="yiyi-st" id="yiyi-475">以下是使用<code class="docutils literal"><span class="pre">GET</span></code>方法检索包含参数的URL的示例会话：</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.parse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">params</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">'spam'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'bacon'</span><span class="p">:</span> <span class="mi">0</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">url</span> <span class="o">=</span> <span class="s2">"http://www.musi-cal.com/cgi-bin/query?</span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">params</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">url</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">))</span>
<span class="gp">...</span>
</code></pre><p><span class="yiyi-st" id="yiyi-476">以下示例使用<code class="docutils literal"><span class="pre">POST</span></code>方法。</span><span class="yiyi-st" id="yiyi-477">请注意，urlencode的params输出在作为数据发送到urlopen之前被编码为字节：</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.parse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">'spam'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'bacon'</span><span class="p">:</span> <span class="mi">0</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">'ascii'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">"http://requestb.in/xrbl82xr"</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">))</span>
<span class="gp">...</span>
</code></pre><p><span class="yiyi-st" id="yiyi-478">以下示例使用明确指定的HTTP代理覆盖环境设置：</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">proxies</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'http'</span><span class="p">:</span> <span class="s1">'http://proxy.example.com:8080/'</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">FancyURLopener</span><span class="p">(</span><span class="n">proxies</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">"http://www.python.org"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">)</span>
<span class="gp">...</span>
</code></pre><p><span class="yiyi-st" id="yiyi-479">以下示例完全不使用代理，覆盖环境设置：</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">FancyURLopener</span><span class="p">({})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">"http://www.python.org/"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">'utf-8'</span><span class="p">)</span>
<span class="gp">...</span>
</code></pre></div><div class="section" id="legacy-interface"><h2><span class="yiyi-st" id="yiyi-480">21.6.24. </span><span class="yiyi-st" id="yiyi-481">旧版接口</span></h2><p><span class="yiyi-st" id="yiyi-482">以下函数和类从Python 2模块<code class="docutils literal"><span class="pre">urllib</span></code>（而不是<code class="docutils literal"><span class="pre">urllib2</span></code>）移植。</span><span class="yiyi-st" id="yiyi-483">他们可能会在将来某个时候被弃用。</span></p><dl class="function"><dt id="urllib.request.urlretrieve"><span class="yiyi-st" id="yiyi-484"> <code class="descclassname">urllib.request.</code><code class="descname">urlretrieve</code><span class="sig-paren">(</span><em>url</em>, <em>filename=None</em>, <em>reporthook=None</em>, <em>data=None</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-485">将由URL表示的网络对象复制到本地文件。</span><span class="yiyi-st" id="yiyi-486">如果URL指向本地文件，则除非提供文件名，否则不会复制该对象。</span><span class="yiyi-st" id="yiyi-487">返回元组<code class="docutils literal"><span class="pre">（filename，</span> <span class="pre">headers）</span></code>其中<em>filename</em>是可以找到对象的本地文件名，<em>headers</em>是返回的<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>返回的对象的<code class="xref py py-meth docutils literal"><span class="pre">info()</span></code>方法（用于远程对象）。</span><span class="yiyi-st" id="yiyi-488">例外情况与<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>相同。</span></p><p><span class="yiyi-st" id="yiyi-489">第二个参数（如果存在）指定要复制到的文件位置（如果不存在，则该位置将是具有生成名称的临时文件）。</span><span class="yiyi-st" id="yiyi-490">第三个参数（如果存在的话）是一个钩子函数，在建立网络连接时会被调用一次，之后每个块被读取一次。</span><span class="yiyi-st" id="yiyi-491">该钩子将传递三个参数；到目前为止传输的块的数量，以字节为单位的块大小以及文件的总大小。</span><span class="yiyi-st" id="yiyi-492">在较旧的FTP服务器上，第三个参数可能是<code class="docutils literal"><span class="pre">-1</span></code>，它们不响应检索请求返回文件大小。</span></p><p><span class="yiyi-st" id="yiyi-493">以下示例说明了最常见的使用场景：</span></p><pre><code class="language-python"><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">local_filename</span><span class="p">,</span> <span class="n">headers</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlretrieve</span><span class="p">(</span><span class="s1">'http://python.org/'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">html</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">local_filename</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">html</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</code></pre><p><span class="yiyi-st" id="yiyi-494">如果<em>url</em>使用<code class="file docutils literal"><span class="pre">http:</span></code>方案标识符，则可以给出可选的<em>data</em>参数来指定一个<code class="docutils literal"><span class="pre">POST</span></code>请求（通常请求类型是<code class="docutils literal"><span class="pre">GET</span></code>）。</span><span class="yiyi-st" id="yiyi-495"><em>data</em>参数必须是标准<em class="mimetype">application / x-www-form-urlencoded</em>格式中的字节对象；请参阅<a class="reference internal" href="urllib.parse.html#urllib.parse.urlencode" title="urllib.parse.urlencode"><code class="xref py py-func docutils literal"><span class="pre">urllib.parse.urlencode()</span></code></a>函数。</span></p><p><span class="yiyi-st" id="yiyi-496"><a class="reference internal" href="#urllib.request.urlretrieve" title="urllib.request.urlretrieve"><code class="xref py py-func docutils literal"><span class="pre">urlretrieve()</span></code></a> will raise <code class="xref py py-exc docutils literal"><span class="pre">ContentTooShortError</span></code> when it detects that the amount of data available was less than the expected amount (which is the size reported by a <em>Content-Length</em> header). </span><span class="yiyi-st" id="yiyi-497">例如，当下载被中断时，会发生这种情况。</span></p><p><span class="yiyi-st" id="yiyi-498">The <em>Content-Length</em> is treated as a lower bound: if there’s more data to read, urlretrieve reads more data, but if less data is available, it raises the exception.</span></p><p><span class="yiyi-st" id="yiyi-499">在这种情况下，您仍然可以检索下载的数据，它存储在异常实例的<code class="xref py py-attr docutils literal"><span class="pre">content</span></code>属性中。</span></p><p><span class="yiyi-st" id="yiyi-500">如果未提供<em>Content-Length</em>标头，则urlretrieve无法检查其下载的数据大小，只是将其返回。</span><span class="yiyi-st" id="yiyi-501">在这种情况下，您只需假定下载成功。</span></p></dd></dl><dl class="function"><dt id="urllib.request.urlcleanup"><span class="yiyi-st" id="yiyi-502"> <code class="descclassname">urllib.request.</code><code class="descname">urlcleanup</code><span class="sig-paren">(</span><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-503">清除先前对<a class="reference internal" href="#urllib.request.urlretrieve" title="urllib.request.urlretrieve"><code class="xref py py-func docutils literal"><span class="pre">urlretrieve()</span></code></a>调用可能遗留的临时文件。</span></p></dd></dl><dl class="class"><dt id="urllib.request.URLopener"><span class="yiyi-st" id="yiyi-504"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">URLopener</code><span class="sig-paren">(</span><em>proxies=None</em>, <em>**x509</em><span class="sig-paren">)</span></span></dt><dd><div class="deprecated"><p><span class="yiyi-st" id="yiyi-505"><span class="versionmodified">自版本3.3起已弃用。</span></span></p></div><p><span class="yiyi-st" id="yiyi-506">打开和阅读URL的基类。</span><span class="yiyi-st" id="yiyi-507">除非需要使用<code class="file docutils literal"><span class="pre">http:</span></code>，<code class="file docutils literal"><span class="pre">ftp:</span></code>或<code class="file docutils literal"><span class="pre">file:</span></code>以外的方案来支持打开对象，否则可能需要使用<a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a></span></p><p><span class="yiyi-st" id="yiyi-508">By default, the <a class="reference internal" href="#urllib.request.URLopener" title="urllib.request.URLopener"><code class="xref py py-class docutils literal"><span class="pre">URLopener</span></code></a> class sends a <em class="mailheader">User-Agent</em> header of <code class="docutils literal"><span class="pre">urllib/VVV</span></code>, where <em>VVV</em> is the <a class="reference internal" href="urllib.html#module-urllib" title="urllib"><code class="xref py py-mod docutils literal"><span class="pre">urllib</span></code></a> version number. </span><span class="yiyi-st" id="yiyi-509">应用程序可以通过继承<a class="reference internal" href="#urllib.request.URLopener" title="urllib.request.URLopener"><code class="xref py py-class docutils literal"><span class="pre">URLopener</span></code></a>或<a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a>并将类属性<a class="reference internal" href="#urllib.request.URLopener.version" title="urllib.request.URLopener.version"><code class="xref py py-attr docutils literal"><span class="pre">version</span></code></a>设置为一个<em class="mailheader">User-Agent</em>子类定义中适当的字符串值。</span></p><p><span class="yiyi-st" id="yiyi-510">可选的<em>代理</em>参数应该是字典映射方案名称到代理URL，其中空字典完全关闭代理。</span><span class="yiyi-st" id="yiyi-511">它的缺省值是<code class="docutils literal"><span class="pre">None</span></code>，在这种情况下，如果存在环境代理设置，将使用上面的<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>定义中讨论的内容。</span></p><p><span class="yiyi-st" id="yiyi-512">在<em>x509</em>中收集的其他关键字参数可用于在使用<code class="file docutils literal"><span class="pre">https:</span></code>方案时对客户端进行身份验证。</span><span class="yiyi-st" id="yiyi-513">支持关键字<em>key_file</em>和<em>cert_file</em>以提供SSL密钥和证书；两者都需要支持客户端身份验证。</span></p><p><span class="yiyi-st" id="yiyi-514"><a class="reference internal" href="#urllib.request.URLopener" title="urllib.request.URLopener"><code class="xref py py-class docutils literal"><span class="pre">URLopener</span></code></a> objects will raise an <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal"><span class="pre">OSError</span></code></a> exception if the server returns an error code.</span></p><span class="yiyi-st" id="yiyi-515"> <blockquote> <div><dl class="method"> <dt id="urllib.request.URLopener.open"> <code class="descname">open</code><span class="sig-paren">(</span><em>fullurl</em>, <em>data=None</em><span class="sig-paren">)</span></dt> <dd><p>Open <em>fullurl</em> using the appropriate protocol. This method sets up cache and proxy information, then calls the appropriate open method with its input arguments. If the scheme is not recognized, <a class="reference internal" href="#urllib.request.URLopener.open_unknown" title="urllib.request.URLopener.open_unknown"><code class="xref py py-meth docutils literal"><span class="pre">open_unknown()</span></code></a> is called. The <em>data</em> argument has the same meaning as the <em>data</em> argument of <a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>.</p> </dd></dl> <dl class="method"> <dt id="urllib.request.URLopener.open_unknown"> <code class="descname">open_unknown</code><span class="sig-paren">(</span><em>fullurl</em>, <em>data=None</em><span class="sig-paren">)</span></dt> <dd><p>Overridable interface to open unknown URL types.</p> </dd></dl> <dl class="method"> <dt id="urllib.request.URLopener.retrieve"> <code class="descname">retrieve</code><span class="sig-paren">(</span><em>url</em>, <em>filename=None</em>, <em>reporthook=None</em>, <em>data=None</em><span class="sig-paren">)</span></dt> <dd><p>Retrieves the contents of <em>url</em> and places it in <em>filename</em>. The return value is a tuple consisting of a local filename and either an <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal"><span class="pre">email.message.Message</span></code></a> object containing the response headers (for remote URLs) or <code class="docutils literal"><span class="pre">None</span></code> (for local URLs). The caller must then open and read the contents of <em>filename</em>. If <em>filename</em> is not given and the URL refers to a local file, the input filename is returned. If the URL is non-local and <em>filename</em> is not given, the filename is the output of <a class="reference internal" href="tempfile.html#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal"><span class="pre">tempfile.mktemp()</span></code></a> with a suffix that matches the suffix of the last path component of the input URL. If <em>reporthook</em> is given, it must be a function accepting three numeric parameters: A chunk number, the maximum size chunks are read in and the total size of the download (-1 if unknown). It will be called once at the start and after each chunk of data is read from the network. <em>reporthook</em> is ignored for local URLs.</p> <p>If the <em>url</em> uses the <code class="file docutils literal"><span class="pre">http:</span></code> scheme identifier, the optional <em>data</em> argument may be given to specify a <code class="docutils literal"><span class="pre">POST</span></code> request (normally the request type is <code class="docutils literal"><span class="pre">GET</span></code>). The <em>data</em> argument must in standard <em class="mimetype">application/x-www-form-urlencoded</em> format; see the <a class="reference internal" href="urllib.parse.html#urllib.parse.urlencode" title="urllib.parse.urlencode"><code class="xref py py-func docutils literal"><span class="pre">urllib.parse.urlencode()</span></code></a> function.</p> </dd></dl> <dl class="attribute"> <dt id="urllib.request.URLopener.version"> <code class="descname">version</code></dt> <dd><p>Variable that specifies the user agent of the opener object. To get <a class="reference internal" href="urllib.html#module-urllib" title="urllib"><code class="xref py py-mod docutils literal"><span class="pre">urllib</span></code></a> to tell servers that it is a particular user agent, set this in a subclass as a class variable or in the constructor before calling the base constructor.</p> </dd></dl> </div></blockquote></span></dd></dl><dl class="class"><dt id="urllib.request.FancyURLopener"><span class="yiyi-st" id="yiyi-516"> <em class="property">class </em><code class="descclassname">urllib.request.</code><code class="descname">FancyURLopener</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span></span></dt><dd><div class="deprecated"><p><span class="yiyi-st" id="yiyi-517"><span class="versionmodified">自版本3.3起已弃用。</span></span></p></div><p><span class="yiyi-st" id="yiyi-518"><a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a>子类<a class="reference internal" href="#urllib.request.URLopener" title="urllib.request.URLopener"><code class="xref py py-class docutils literal"><span class="pre">URLopener</span></code></a>为以下HTTP响应代码提供了默认处理：301,302,303,307和401。</span><span class="yiyi-st" id="yiyi-519">对于上面列出的30x响应代码，<em class="mailheader">Location</em>标头用于获取实际的URL。</span><span class="yiyi-st" id="yiyi-520">对于401响应代码（需要认证），执行基本的HTTP认证。</span><span class="yiyi-st" id="yiyi-521">对于30x响应代码，递归受到<em>maxtries</em>属性值的限制，默认值为10。</span></p><p><span class="yiyi-st" id="yiyi-522">对于所有其他响应代码，调用方法<code class="xref py py-meth docutils literal"><span class="pre">http_error_default()</span></code>，您可以在子类中重写该方法以正确处理错误。</span></p><div class="admonition note"><p class="first admonition-title"><span class="yiyi-st" id="yiyi-523">注意</span></p><p class="last"><span class="yiyi-st" id="yiyi-524">根据<span class="target" id="index-8"></span> <a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>的字母，301和302对POST请求的响应不得在未经用户确认的情况下自动重定向。</span><span class="yiyi-st" id="yiyi-525">实际上，浏览器确实允许自动重定向这些响应，将POST更改为GET，并且<a class="reference internal" href="urllib.html#module-urllib" title="urllib"><code class="xref py py-mod docutils literal"><span class="pre">urllib</span></code></a>重现了这种行为。</span></p></div><p><span class="yiyi-st" id="yiyi-526">构造函数的参数与<a class="reference internal" href="#urllib.request.URLopener" title="urllib.request.URLopener"><code class="xref py py-class docutils literal"><span class="pre">URLopener</span></code></a>的参数相同。</span></p><div class="admonition note"><p class="first admonition-title"><span class="yiyi-st" id="yiyi-527">注意</span></p><p class="last"><span class="yiyi-st" id="yiyi-528">在执行基本身份验证时，<a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a>实例会调用其<a class="reference internal" href="#urllib.request.FancyURLopener.prompt_user_passwd" title="urllib.request.FancyURLopener.prompt_user_passwd"><code class="xref py py-meth docutils literal"><span class="pre">prompt_user_passwd()</span></code></a>方法。</span><span class="yiyi-st" id="yiyi-529">默认实现向用户询问控制终端上的所需信息。</span><span class="yiyi-st" id="yiyi-530">如果需要，子类可以重写此方法以支持更适当的行为。</span></p></div><p><span class="yiyi-st" id="yiyi-531"><a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a>类提供了一个应该重载以提供适当行为的附加方法：</span></p><dl class="method"><dt id="urllib.request.FancyURLopener.prompt_user_passwd"><span class="yiyi-st" id="yiyi-532"> <code class="descname">prompt_user_passwd</code><span class="sig-paren">(</span><em>host</em>, <em>realm</em><span class="sig-paren">)</span></span></dt><dd><p><span class="yiyi-st" id="yiyi-533">返回在指定的安全领域中对给定主机上的用户进行身份验证所需的信息。</span><span class="yiyi-st" id="yiyi-534">返回值应该是一个元组，<code class="docutils literal"><span class="pre">（user，</span> <span class="pre">password）</span></code>，它可以用于基本认证。</span></p><p><span class="yiyi-st" id="yiyi-535">实施提示在终端上提供这些信息；应用程序应该重写此方法以在本地环境中使用适当的交互模型。</span></p></dd></dl></dd></dl></div><div class="section" id="urllib-request-restrictions"><h2><span class="yiyi-st" id="yiyi-536">21.6.25. <a class="reference internal" href="#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal"><span class="pre">urllib.request</span></code></a> Restrictions</span></h2><ul id="index-9"><li><p class="first"><span class="yiyi-st" id="yiyi-537">目前，仅支持以下协议：HTTP（版本0.9和1.0），FTP，本地文件和数据URL。</span></p><div class="versionchanged"><p><span class="yiyi-st" id="yiyi-538"><span class="versionmodified">版本3.4已更改：</span>增加了对数据网址的支持。</span></p></div></li><li><p class="first"><span class="yiyi-st" id="yiyi-539"><a class="reference internal" href="#urllib.request.urlretrieve" title="urllib.request.urlretrieve"><code class="xref py py-func docutils literal"><span class="pre">urlretrieve()</span></code></a>的缓存功能已被禁用，直到有人找到时间来破解对过期时间标头的正确处理。</span></p></li><li><p class="first"><span class="yiyi-st" id="yiyi-540">应该有一个函数来查询一个特定的URL是否在缓存中。</span></p></li><li><p class="first"><span class="yiyi-st" id="yiyi-541">为了向后兼容，如果URL看起来指向本地文件，但文件无法打开，则使用FTP协议重新解释URL。</span><span class="yiyi-st" id="yiyi-542">这有时会导致混淆错误消息。</span></p></li><li><p class="first"><span class="yiyi-st" id="yiyi-543"><a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>和<a class="reference internal" href="#urllib.request.urlretrieve" title="urllib.request.urlretrieve"><code class="xref py py-func docutils literal"><span class="pre">urlretrieve()</span></code></a>函数会在等待网络连接建立时导致任意长的延迟。</span><span class="yiyi-st" id="yiyi-544">这意味着使用这些函数而不使用线程来构建交互式Web客户端是很困难的。</span></p></li><li id="index-10"><p class="first"><span class="yiyi-st" id="yiyi-545">由<a class="reference internal" href="#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal"><span class="pre">urlopen()</span></code></a>或<a class="reference internal" href="#urllib.request.urlretrieve" title="urllib.request.urlretrieve"><code class="xref py py-func docutils literal"><span class="pre">urlretrieve()</span></code></a>返回的数据是服务器返回的原始数据。</span><span class="yiyi-st" id="yiyi-546">这可能是二进制数据（如图像），纯文本或（例如）HTML。</span><span class="yiyi-st" id="yiyi-547">HTTP协议在回复标题中提供了类型信息，可以通过查看<em class="mailheader">Content-Type</em>标题进行检查。</span><span class="yiyi-st" id="yiyi-548">如果返回的数据是HTML，那么可以使用模块<a class="reference internal" href="html.parser.html#module-html.parser" title="html.parser: A simple parser that can handle HTML and XHTML."><code class="xref py py-mod docutils literal"><span class="pre">html.parser</span></code></a>来解析它。</span></p></li><li id="index-11"><p class="first"><span class="yiyi-st" id="yiyi-549">处理FTP协议的代码不能区分文件和目录。</span><span class="yiyi-st" id="yiyi-550">当尝试读取指向无法访问的文件的URL时，这可能会导致意外的行为。</span><span class="yiyi-st" id="yiyi-551">如果URL以<code class="docutils literal"><span class="pre">/</span></code>结尾，则假定引用一个目录并将相应处理。</span><span class="yiyi-st" id="yiyi-552">但是，如果尝试读取文件导致550错误（意思是无法找到URL或者由于权限原因而无法访问该URL），那么该路径将被视为目录以处理指定目录时的情况通过一个URL，但是尾部的<code class="docutils literal"><span class="pre">/</span></code>已经被关闭。</span><span class="yiyi-st" id="yiyi-553">当您尝试获取读取权限使其无法访问的文件时，这可能会导致误导性结果； FTP代码将尝试读取它，以550错误失败，然后执行不可读文件的目录列表。</span><span class="yiyi-st" id="yiyi-554">如果需要细粒度控制，请考虑使用<a class="reference internal" href="ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal"><span class="pre">ftplib</span></code></a>模块，继承<a class="reference internal" href="#urllib.request.FancyURLopener" title="urllib.request.FancyURLopener"><code class="xref py py-class docutils literal"><span class="pre">FancyURLopener</span></code></a>或更改<em>_urlopener</em>以满足您的需求。</span></p></li></ul></div></div><div class="section" id="module-urllib.response"><h1><span class="yiyi-st" id="yiyi-555">21.7.  <a class="reference internal" href="#module-urllib.response" title="urllib.response: Response classes used by urllib."><code class="xref py py-mod docutils literal"><span class="pre">urllib.response</span></code></a>  -  urllib使用的响应类</span></h1><p><span class="yiyi-st" id="yiyi-556">The <a class="reference internal" href="#module-urllib.response" title="urllib.response: Response classes used by urllib."><code class="xref py py-mod docutils literal"><span class="pre">urllib.response</span></code></a> module defines functions and classes which define a minimal file like interface, including <code class="docutils literal"><span class="pre">read()</span></code> and <code class="docutils literal"><span class="pre">readline()</span></code>. </span><span class="yiyi-st" id="yiyi-557">典型的响应对象是addinfourl实例，它定义了一个<code class="docutils literal"><span class="pre">info()</span></code>方法，并返回标头和一个返回url的<code class="docutils literal"><span class="pre">geturl()</span></code>方法。</span><span class="yiyi-st" id="yiyi-558">由该模块定义的函数由<a class="reference internal" href="#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal"><span class="pre">urllib.request</span></code></a>模块内部使用。</span></p></div></div>